2014-07-06 41 views
0

我在项目中有一个列表,带有一个滚动条。还有一个按钮。所以当按下按钮时,滚动会移动到给定的ID以使其可见。我看了类似的解决方案,但无法让我的工作。如何通过jQuery将滚动条移动到某个地方

这里是我的代码:

function next() { 
    $("#example").css("background", "red"); 
} 

function goToByScroll(id) { 
    // Reove "link" from the ID 
    // Scroll 
    $('ul').animate({ 
     scrollTop: $("#" + id).offset().top() 
    }, 
     'slow'); 
} 

$("button").click(function (e) { 
    // Prevent a page reload when a link is pressed 
    e.preventDefault(); 
    // Call the scroll function 
    goToByScroll("example"); 
}); 

HTML:

<ul> 
    <li>Name1</li> 
    <li>Name2</li> 
    <li>Name3</li> 
    <li>Name4</li> 
    <li>Name5</li> 
    <li>Name6</li> 
    <li>Name7</li> 
    <li id="example">Name8</li> 
    <li>Name9</li> 
    <li>Name10</li> 
</ul> 
<button onClick="next()">Next</button> 

http://jsfiddle.net/danials/f2UZT/ 任何想法,使其正常工作?它必须作为一个函数工作,所以函数值将是一个ID,所以它移动到持有ID的元素。

+1

代替偏移()。顶()'使用' offset()。top',只需从顶端删除'()' –

回答

1

而不是

scrollTop: $("#" + id).offset().top()

使用此

scrollTop: $("#" + id).offset().top

,避免li去向上使用li高度, 所以你的最终代码会

$('ul').animate({ 
     scrollTop: $("#" + id).offset().top - $("#" + id).height() 
},'slow'); 

工作的`DEMO

+0

感谢您的帮助。它的工作。但这不是很准确。无论如何要让它准确。我尝试了不同的类,有时它会找到该类,但是滚动到比元素高或低一点,所以元素会跳出框。无论如何想法? –

+1

@DanielJJ:回答更新:) –

0

您可以使用此滚动

$.fn.scrollView = function() { 
    return this.each(function() { 
    $('html, body').animate({ 
    scrollTop: $(this).offset().top 
    }, 1000); 
}); 
} 

而对于目标按钮和目标位置

$('#post-1').click(function (event) { 
    event.preventDefault(); 
    $('#contact').scrollView(); 
}); 
相关问题