![](/img/trans.png)
[英]Jquery/JS : How to prevent scrolling in parent element while the child is scrollable (mobile)?
[英]Scrolling to the child element of a scrollable parent
我有一個可滾動的ul
和幾個li
項目。 我的目標是當用戶按下按鈕時滾動到具有特定ID的li
-item。
我有一個似乎有效的代碼,但是有兩個問題
我猜這兩個問題都是由於某些相對坐標造成的,但我無法弄清楚該系統的工作原理。 請幫幫我!
HTML:
<ul id="container">
<li id="1">stuff1</li>
<li id="2">stuff2</li>
<li id="3">stuff3</li>
<li id="4">stuff4</li>
<li id="5">stuff5</li>
<li id="6">stuff6</li>
<li id="7">stuff7</li>
<li id="8">stuff8</li>
<li id="9">stuff9</li>
<li id="10">stuff10</li>
<li id="11">stuff11</li>
<li id="12">stuff12</li>
<li id="13">stuff13</li>
<li id="14">stuff14</li>
<li id="15">stuff15</li>
<li id="16">stuff16</li>
</ul>
<button id = 'btn'>Scroll to element with id = 9</button>
JS:
var $container = $('#container')[0];
// $container.scrollTop = $container.scrollHeight;
// If I uncomment the above line, the code does not work any more
$('#btn').click(function(){
$container.scrollTop = $('#9').position().top;
});
CSS:
ul {
overflow-y: auto;
position: relative;
height: 300px;
width: 300px;
background: red;
}
ul li {
margin: 30px;
border: solid;
}
參見JSFiddle
9元素也將相對於滾動條定位。 您必須將當前滾動添加到9位置,如下所示: http : //jsfiddle.net/rck1ow93/2/
$container.scrollTop = $container.scrollTop+$('#9').position().top;
為了增加Jorge的答案,除了考慮滾動之外,您可能還想使用.offset()而不是.position(),因為它將為您提供正確的位置。 所以改變
$container.scrollTop = $('#9').position().top;
至
$container.scrollTop += $('#9').offset().top;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.