这是一个简单的自动完成搜索栏,当用户输入时显示建议。用户可以使用向下或向上方向键在所有建议中导航。但是这个建议框的最大高度只有300px。所以我要让它沿y轴滚动。我希望当用户浏览建议时,div应该滚动,以便用户可以浏览所有建议。JS小提琴
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Autocomplete</h2>
<p>Start typing:</p>
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input type="submit">
</form>
</body>
</html>
如果你不能将自动完成设置为默认值,那么你可以这样做
https://jsfiddle.net/mplungjan/c3hkfLyq/
document.getElementById("myInput").addEventListener("keydown",function(e) {
const scroll = ["ArrowUp","ArrowDown"].includes(e.key)
const list = document.getElementById("myInputautocomplete-list")
if (scroll) {
document.querySelector(".autocomplete-active").scrollIntoView()
}
})