2014-11-06 77 views
0

這是虛擬代碼。我的要求是當我點擊最後的li元素,然後一個hidden div裏面會顯示。但我需要scroll下來才能看到它。 所以當我點擊liid=hello然後窗口應該自動向下滾動到該div?如何使用CSS/JS滾動到特定元素

首選使用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>

+0

你需要它是動畫? – 2014-11-06 07:05:02

+0

任何東西。只需要自動滾動到該div。 – 2014-11-06 07:07:34

+0

那麼,我會嘗試的第一件事就是在你的''hello''''裏面放一個簡單的錨元素,並將它的'href'屬性設置爲'#myHiddenDivsId'。它不需要JS。 – 2014-11-06 07:16:25

回答

3

告訴你/你的擴展隱藏DIV,調用li元素 這不需要的jQuery的scrollIntoView功能之後。

function showIt(el_id) { 
    var el = document.getElementById(el_id); 
    el.scrollIntoView(true); 
} 

欲瞭解更多請參考https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView

+0

你可以使用CSS提供解決方案嗎? +1這JS解決方案 – 2014-11-06 07:16:27

+0

@ShoaibChikate我懷疑你可以使用CSS滾動div。雖然您可以在div滾動時使用css效果。但你實際上不能用css設置滾動值。 – shinobi 2014-11-06 07:24:17

1

您可以使用錨重定向window.location = currentlocation + "#" + id,或者您可以使用jQuery的lib - scrollTo

編輯: 我讀它cannnot是jQuery的。試試這個:

ele.addEventListener("click", function (event) { 
    document.getElementById("hidden-div").style.display="block"; 
    window.location.href = window.location.href + "#hidden-div"; 
},false); 
+0

你可以使用CSS提供解決方案嗎? +1這個JS解決方案。 – 2014-11-06 07:18:15

+0

不幸的是,沒有使用CSS的解決方案。 – bemol 2014-11-06 07:38:05

0
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);