如何减少和增加滚动页边距

How in decrease and increase the margin on scroll

本文关键字:滚动 页边距 增加 何减少      更新时间:2023-09-26

我想编写javascript代码,当窗口向上滚动时,通过减小页边空白顶部(默认值为0)来向上移动文本。但当我向下滚动时,文本顶部的边距不等于0。请帮助

Fiddle示例

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);

您不需要逐像素添加。您可以直接从滚动条顶部设置文本边距:

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);

固定示例