我在项目中有一个列表,带有一个滚动条。还有一个按钮。所以当按下按钮时,滚动会移动到给定的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的元素。
代替偏移()。顶()'使用' offset()。top',只需从顶端删除'()' –