gpt4 book ai didi

javascript - 在弹出项上移动时自动滚动

转载 作者:行者123 更新时间:2023-11-28 14:36:28 24 4
gpt4 key购买 nike

我有以下代码。我在菜单项弹出窗口中添加了 overflow-y 和 max-height css 属性。在搜索文本框中键入“a”并按下键时,元素选择会相应更改。但是滚动没有移动。我希望在弹出菜单项上移动时滚动自动移动

#myInputautocomplete-list{
max-height:200px !important;
overflow-y:auto !important;
}

<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input type="submit">

Here Plnfkr

最佳答案

您可以使用 Element.scrollIntoView() 它可以帮助您在这种情况下滚动。我在函数 inp.addEventListener("keydown", function(e)

的末尾添加了这两行
if(x && x[currentFocus])
x[currentFocus].scrollIntoView();
  • 我 fork 了 Pinfkr here
  • 可以找到关于 scrollIntoView 的文档 here

更新:

It change scroll while we are on first element. It should change the scroll when item inside popup selection across the popup boundary

我通过添加一个函数来检查滚动元素是否可见来解决这个问题,只有当元素在下拉列表中不可见时才会应用滚动移动。

// Return true/false if element is visible in relation to a given scrolling container
// Use to see if an element is visible within a scrolling div for example.
function isScrolledElementVisible(o_ele, o_container){
var v_containerTop = o_container.scrollTop;
var v_containerBottom = v_containerTop + o_container.offsetHeight;
var v_elemTop = o_ele.offsetTop;
var v_elemBottom = o_ele.offsetTop + o_ele.offsetHeight;
return ((v_elemBottom >= v_containerTop) && (v_elemTop <= v_containerBottom)
&& (v_elemBottom <= v_containerBottom) && (v_elemTop >= v_containerTop) );
}

作为引用,我从 here 得到了那个函数

Also if there is another scroll inside the page it also apply to them also

为了解决这个问题,我只手动设置下拉列表的 scrollTop 而不是使用 scrollIntoView() 以便其他滚动不受影响

  var topPos = x[currentFocus].offsetTop;
o_container.scrollTop = topPos;

我从 here 学会了如何不依赖 scrollIntoView()

我又fork了Pinfkr 可以找到here

关于javascript - 在弹出项上移动时自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53425058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com