【发布时间】:2019-03-26 00:57:30
【问题描述】:
我想模仿 jQuery 的行为,就像你在这里看到的那样: http://edo.webmaster.am/
只需看一下右下角,向下滚动一下,您就会看到“返回顶部”按钮。
所以它是不可见的,直到您向下滚动页面然后它出现(动画)。
如何在 jQuery 中做到这一点?
【问题讨论】:
我想模仿 jQuery 的行为,就像你在这里看到的那样: http://edo.webmaster.am/
只需看一下右下角,向下滚动一下,您就会看到“返回顶部”按钮。
所以它是不可见的,直到您向下滚动页面然后它出现(动画)。
如何在 jQuery 中做到这一点?
【问题讨论】:
您可以监控当前窗口滚动位置并采取相应措施。如果您希望偏移量在某个点之后(下面的代码将进行任何滚动,甚至 1px),那么只需检查 if 语句中的 $(this).scrollTop() > n,其中 n 是所需的偏移量。
http://jsfiddle.net/robert/fjXSq/
$(window).scroll(function() {
if ($(this).scrollTop()) {
$('#toTop:hidden').stop(true, true).fadeIn();
} else {
$('#toTop').stop(true, true).fadeOut();
}
});
【讨论】:
.scrollTop() > n 的淡出问题,请在.fadeOut() 之前添加if ($('#toTop').css('display') == none)
$(this) 对我不起作用。可能是因为我在 TypeScript Angular 组件中使用它。将 $(this) 更改为 $(window) 对我有用。
老问题,但我想,因为我为自己实施了一个给我的两分钱。我相信最好使用 setTimeout 对多个触发事件进行安全防护。像这样:
function showButton() {
var button = $('#my-button'), //button that scrolls user to top
view = $(window),
timeoutKey = -1;
$(document).on('scroll', function() {
if(timeoutKey) {
window.clearTimeout(timeoutKey);
}
timeoutKey = window.setTimeout(function(){
if (view.scrollTop() < 100) {
button.fadeOut();
}
else {
button.fadeIn();
}
}, 100);
});
}
$('#my-button').on('click', function(){
$('html, body').stop().animate({
scrollTop: 0
}, 500, 'linear');
return false;
});
//call function on document ready
$(function(){
showButton();
});
【讨论】: