我正在尝试使用一个按钮将页面滚动到给定元素id
。我目前有Fiddle,但我希望它有所不同:
#three
)的底部位于页面底部,而不是div的顶部滚动到页面顶部。如何做到这一点?
HTML
<button id="btn">CLICK</button>
<div class="test" id="one"></div>
<div class="test" id="two"></div>
<div class="test" id="three"></div>
<div class="test" id="four"></div>
CSS
.test {
width: 100%;
height: 400px;
}
#one { background: red; }
#two { background: green; }
#three { background: blue; }
#four { background: yellow; }
JS
$("#btn").click(function() {
$('html, body').animate({
scrollTop: $("#three").offset().top
}, 500);
});
答案 0 :(得分:5)
好的,这是第一部分 -
$('html, body').animate({
scrollTop: ($("#three").offset().top + $("#three").height() - $(window).height())
}, 500);
只是一点点数学,你可以很容易地自己理解正在发生的事情。
和第二部分 -
if(($('#three').offset().top >= $(window).scrollTop()) && ($('#three').offset().top < $(window).scrollTop() + $(window).height())) { ...
}
值的复杂比较,用于检查元素的顶部偏移位于窗口scrollTop()和+ window height()之间的可见性(即类似于窗口的偏移底部)。
查看fiddle
更新:上一个中存在错误,您需要一个额外的条件语句来检查#three
的可见性,方法是考虑窗口scrollTop()之间元素的底部偏移量窗口的底部偏移。所以完整的条件将成为 -
var eloffbottom = $('#three').offset().top + $('#three').height();
var winoffbottom = $(window).scrollTop() + $(window).height();
if((($('#three').offset().top >= $(window).scrollTop()) && ($('#three').offset().top < winoffbottom)) || ((eloffbottom >= $(window).scrollTop()) && (eloffbottom < winoffbottom))) {
alert('already in view');
}
UPDATED Fiddle完全正常工作!
顺便说一下,刚刚发现了一个jQuery插件,可以为你做到这一点。 See here。只需将其用作 - $('#three').visible()
- 返回true或false。
答案 1 :(得分:2)
通过从元素的偏移顶部减去窗口高度然后添加元素高度来计算顶部。
$("#btn").click(function() {
var winHeight = $(window).height(),
topOffset = $("#three").offset().top,
elementHeight = $('#three').height()
var top = topOffset - winHeight + elementHeight;
$('html, body').animate({
scrollTop: top
}, 500);
});
.test {
width: 100%;
height: 400px;
}
#one {
background: red;
}
#two {
background: green;
}
#three {
background: blue;
border: solid 3px gray;
}
#four {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button id="btn">CLICK</button>
<div class="test" id="one"></div>
<div class="test" id="two"></div>
<div class="test" id="three"></div>
<div class="test" id="four"></div>