gpt4 book ai didi

javascript - 根据 div id 滚动位置滑入滑出元素

转载 作者:行者123 更新时间:2023-11-30 20:36:25 25 4
gpt4 key购买 nike

我试图在 div 到达浏览器顶部时隐藏和显示元素。我阅读了几个线程并编写了这段代码

function hidebtn() {
var scrollTop = $(window).scrollTop(),
elementOffset = $('.triger').offset().top,
distance = (elementOffset - scrollTop);

var x = document.getElementById("u94");

if (distance < 1) {
$(x).animate({'top': '-100px'}, 300);
} else {
$(x).animate({'top': '0px'}, 300);
}
}

window.onscroll = hidebtn

出于同样的原因,它不起作用,或者更具体地说,它会延迟很长时间。

如果我将条件代码更改为

if (distance < 1 ) {
x.style.display = "none";
} else {
x.style.display = "block";
}

它工作正常,但我真的很喜欢使用滑动动画

你可以在JSFIddle中看到它

有什么建议吗?

最佳答案

onscroll 在用户滚动时被多次调用。您可以设置一点超时来删除过多的调用:

var scrollTimer = null;

function hidebtn() {

if (scrollTimer) {
clearTimeout(scrollTimer); // clear previous timer
}

// set timer while we wait for a pause in scroll events
scrollTimer = setTimeout(function() {
scrollTimer = null; // timer done here
console.log("ok");

var scrollTop = $(window).scrollTop(),
elementOffset = $('.triger').offset().top,
distance = (elementOffset - scrollTop);

var x = document.getElementById("u94");

if (distance < 1) {
$(x).animate({'top': '-100px'}, 300);
} else{
$(x).animate({'top': '0px'}, 300);
}
}, 100); // delay time
}

window.onscroll = hidebtn

这是一个有效的 fiddle

关于javascript - 根据 div id 滚动位置滑入滑出元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com