2017-03-13 10 views
2

스크롤 할 수있는 ul과 여러 개의 li -item이 있습니다. 내 목표는 사용자가 버튼을 누를 때 li -item으로 특정 ID로 스크롤하는 것입니다.스크롤 할 수있는 부모의 자식 요소로 스크롤

나는 작동하는 것 같다 코드를 가지고,하지만 난 페이지가로드 목록의 끝에 아래로 스크롤하면 버튼이 더 이상 작동하지 않는 두 가지 문제

  1. 이있다. 코드에서 언급 한대로 주석을 달고 코드에서 언급 한대로 주석을 제거하십시오.
  2. 목록의 원하는 항목을 이미 사용하고 있다면 스크롤 단추를 눌러도 같은 위치를 유지하고 싶습니다.

두 가지 문제는 상대 좌표로 인한 것 같지만이 시스템의 작동 방식을 알 수 없습니다. 도와주세요, 제발!

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

답변

5

9 개의 요소가 너무 스크롤에 대해 위치 될 참조. 이 같은 9 위치로 현재 스크롤을 추가해야합니다 : http://jsfiddle.net/rck1ow93/2/

$container.scrollTop = $container.scrollTop+$('#9').position().top; 
1

, 당신은 대신 .position의) (.offset 사용할 수있는 계정으로 스크롤을 복용하는 것 외에도, 호르헤의 대답에 추가하려면() 올바른 위치를 알려줄 것입니다. 그래서

$container.scrollTop += $('#9').offset().top; 

http://jsfiddle.net/t06fjtqd/

$container.scrollTop = $('#9').position().top; 

변경

관련 문제