如何使用CSS/JS滚动到特定元素

How to scroll to particular element using CSS/JS

本文关键字:元素 滚动 JS 何使用 CSS      更新时间:2023-09-26

这是伪代码。我的要求是,当我点击最后一个li元素时,会显示其中的一个hidden div。但我需要scroll才能看到它。所以当我用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

您可以使用锚点重定向window.location = currentlocation + "#" + id,也可以使用jquery lib-scrollTo

编辑:我读到它不可能是jQuery。试试这个:

ele.addEventListener("click", function (event) {
    document.getElementById("hidden-div").style.display="block";
    window.location.href = window.location.href + "#hidden-div";
},false);
var ele=document.getElementById('hello');
ele.addEventListener("click", function (event) {
    document.getElementById("hidden-div").style.display="block";
    var top = this.offsetTop;
    this.parentNode.scrollTop += top; //Container div scroll
    document.body.scrollTop += top; //Body scroll
},false);