스크롤 할 수있는 ul
과 여러 개의 li
-item이 있습니다. 내 목표는 사용자가 버튼을 누를 때 li
-item으로 특정 ID로 스크롤하는 것입니다.스크롤 할 수있는 부모의 자식 요소로 스크롤
나는 작동하는 것 같다 코드를 가지고,하지만 난 페이지가로드 목록의 끝에 아래로 스크롤하면 버튼이 더 이상 작동하지 않는 두 가지 문제
- 이있다. 코드에서 언급 한대로 주석을 달고 코드에서 언급 한대로 주석을 제거하십시오.
- 목록의 원하는 항목을 이미 사용하고 있다면 스크롤 단추를 눌러도 같은 위치를 유지하고 싶습니다.
두 가지 문제는 상대 좌표로 인한 것 같지만이 시스템의 작동 방식을 알 수 없습니다. 도와주세요, 제발!
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