这是伪代码。我的要求是,当我单击最后一个 li
元素时,将显示其中的一个 hidden div
。但我需要向下滚动 到它看见。
所以当我用
id=hello
点击 li
时,窗口应该自动向下滚动到那个 div?
首选使用 CSS,然后是 JS,不使用 jQuery。
var ele=document.getElementById('hello');
ele.addEventListener("click", function (event) {
document.getElementById("hidden-div").style.display="block";
},false);
.fixed-height-div{
height:120px;
overflow-y:scroll;
}
.fixed-height-div > li{
background-color:lightblue;
list-style-type: none;
}
<div class="fixed-height-div">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
<li id="hello">H
<div id="hidden-div" style="display:none;">
This should be displayed after click<br><br>
And the scroll should come to this screen.
</div>
</li>
最佳答案
在显示/展开隐藏的 div 之后,调用 li
元素的 scrollIntoView
函数
这不需要 jQuery。
function showIt(elementId) {
var el = document.getElementById(elementId);
el.scrollIntoView(true);
}
有关更多信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView
关于javascript - 如何使用 CSS/JS 滚动到特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773423/