gpt4 book ai didi

jquery - 请细化: Follow scroll but sticky on top

转载 作者:行者123 更新时间:2023-12-01 01:34:47 25 4
gpt4 key购买 nike

我已经完成了我想做的事情:使元素跟随鼠标滚动。如果您快速向下滚动,该元素会暂时消失在视线中,然后随着滚动回到其原始位置。这是第一个 fiddle : http://jsfiddle.net/s4Tsy/

我还成功地使元素粘在顶部。如果我们现在快速滚动,它永远不会消失。这是一个 fiddle :http://jsfiddle.net/aRnAe/

我的问题是:这可以做得更优雅吗?我确信这段代码很笨拙。我是新手,想学习。

$(document).ready(function(){
var el=$('#scrolldiv');
var originalelpos = el.offset().top;
var scrolltimer;
//run on scroll
$(window).scroll(function(){
var el=$('#scrolldiv'); // important! (local)
var windowpos = $(window).scrollTop();
var currentpos = el.offset().top;
if(windowpos>=currentpos)
{
el.addClass('scrollfixed');
}
else
{
var finaldestination = windowpos+originalelpos;
el.stop().animate({'top':finaldestination},2500);
}
clearTimeout(scrolltimer);
scrolltimer = setTimeout(afterScroll, 100);
});
function afterScroll() {
currentpos = el.offset().top;
windowpos = $(window).scrollTop();
if (currentpos <= windowpos) {
el.removeClass('scrollfixed');
el.css({top: windowpos });
finaldestination = windowpos+originalelpos;
el.stop().animate({'top':finaldestination},1000);
}
}
});

亲切的问候,斯蒂芬

最佳答案

这是结果。

<强> >> A jsfiddle of the code below

我相信 CME64 的说法,代码没问题。

脚本

$(document).ready(function(){
var el = $('#scrolldiv');
var originalelpos = el.offset().top;
var scrolltimer;
//run on scroll
$(window).scroll(function () {
var windowpos = $(window).scrollTop();
var currentpos = el.offset().top;
if (windowpos >= currentpos) {
el.addClass('scrollfixed');
} else if(currentpos >= $(window).scrollTop() + $(window).height() - el.height() ){
el.addClass('scrollfixedBtm');
}else{
var finaldestination = windowpos + originalelpos;
el.stop().animate({
'top': finaldestination
}, 500);
}
clearTimeout(scrolltimer);
scrolltimer = setTimeout(afterScroll, 100);
});

function afterScroll() {
currentpos = el.offset().top;
windowpos = $(window).scrollTop();
if (currentpos <= windowpos) {
el.removeClass('scrollfixed');
el.css({
top: windowpos
});
finaldestination = windowpos + originalelpos;
el.stop().animate({
'top': finaldestination
}, 500);
}else if (currentpos >= $(window).scrollTop() + $(window).height() - el.height()){
el.removeClass('scrollfixedBtm');
el.css({
top: (windowpos+$(window).height()-el.height())
});
finaldestination = windowpos + originalelpos;
el.stop().animate({
'top': finaldestination
}, 500);
}
}
});

CSS

.scrollfixed {
position: fixed !important;
top: 0px !important;
}
.scrollfixedBtm {
position: fixed !important;
top: 90% !important;
}
#scrolldiv {
position: absolute;
height: 100px;
width: 30px;
background-color: #f00;
left:0;
top: 100px;
}

* HTML *(当然效果仅在长滚动页面中可见)

<div id="scrolldiv"></div>

关于jquery - 请细化: Follow scroll but sticky on top,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17163874/

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