gpt4 book ai didi

javascript - 如何减少和增加滚动边距

转载 作者:行者123 更新时间:2023-12-03 11:35:15 26 4
gpt4 key购买 nike

我想编写 javascript 代码,以在窗口向上滚动时通过减小 margin-top (默认为 0)来向上移动文本。但是当我向下滚动时,文本的 margin-top 不等于 0。请帮助

Fiddle Example

HTML:

<div id="h">
<div id="t">Hello</div>
<div id="content"></div>

CSS:

#h {
background:green;
width:550px;
height:200px;
position:fixed;
top:0;
padding:50px 0 0 100px;
}
#t {
font-size:40px;
color:white;
}
#content {
background:blue;
width:550px;
height:700px;
margin:200px 0;
position:relative;
}

JS:

var pos = 0;
var el = document.getElementById("t");
var m = 0;
window.addEventListener("scroll", function () {
if (window.pageYOffset > pos) {
m -= 1;
el.style.marginTop = m + "px";
} else {
m += 1;
el.style.marginTop = m + "px";
}
pos = window.pageYOffset;
}, false);

最佳答案

您不需要逐像素添加。您可以直接从scrollTop设置文本边距:

var pos = 0;
var el = document.getElementById("t");
var m = 0;
window.addEventListener("scroll", function () {
el.style.marginTop = -window.pageYOffset/2 + "px";
pos = window.pageYOffset;
}, false);

Fixed Example

关于javascript - 如何减少和增加滚动边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26544094/

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