簡體   English   中英

如何使用CSS / JS滾動到特定元素

[英]How to scroll to particular element using CSS/JS

這是偽代碼。 我的要求是,當我單擊最后一個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/zh-CN/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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM