我有一个包含其他几个 div 的 div,我希望能够让单击哪个 div 滚动到包含 div 的顶部。
我不想简单地滚动到 div 的顶部,这将是 scrollTop:0,我希望无论单击哪个 div,该 div 都会滚动到顶部。
使用 scrollTop: $(this).offset().top 只给出相对于容器的偏移量,所以它是不正确的,因为它只返回一个相对较小的值。
这是设置:
<div id="container" style="position:relative; height:400px; width:100%; overflow:auto;">
<div id="div1" class="clicker" style="height: 1000px; width 100px; ; background:blue">
Test
</div>
<div id="div2" class="clicker" style="height: 1000px; width 100px; background:green">
Test 2
</div>
<div id="div3" class="clicker" style="height: 1000px; width 100px; background:yellow">
Test 3
</div>
</div>
用这个 JS:
$(".clicker").click(function ()
{
$('#container').animate({
scrollTop: WHAT GOES HERE?
}, 2000);
});
这是 jsfiddle:
干杯
最佳答案
需要结合容器当前滚动位置和div的位置
var container = $('#container');
$(".clicker").click(function () {
var top = $(this).position().top,
currentScroll = container.scrollTop();
container.animate({
scrollTop: currentScroll + top
}, 1000);
});
演示在 http://jsfiddle.net/ucag9dos/2
本地演示:
$(function() {
var container = $('#container');
$(".clicker").click(function() {
var top = $(this).position().top,
currentScroll = container.scrollTop();
container.animate({
scrollTop: currentScroll + top
}, 1000);
});
});
#container {
position: relative;
height: 400px;
width: 100%;
overflow: auto;
background: red
}
.clicker {
height: 1000px;
width: 100%;
}
#div1 {
background: blue
}
#div2 {
background: green
}
#div3 {
background: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="div1" class="clicker">Test</div>
<div id="div2" class="clicker">Test 2</div>
<div id="div3" class="clicker">Test 3</div>
</div>
另一种方法是添加所有先前 sibling 的高度。
关于javascript - 在 div jquery 中滚动到 div 的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100423/