【问题标题】:How in decrease and increase the margin on scroll如何减少和增加滚动边距
【发布时间】:2014-10-24 17:02:30
【问题描述】:

当窗口向上滚动时,我想编写 javascript 代码通过减小顶部边距(默认为 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);

【问题讨论】:

  • 告诉我们你到目前为止做了什么。
  • 您想解释一下为什么要更改页面滚动时的文本边距吗?反正文字会上去,你的逻辑是什么?
  • 你知道如何在这里发布 jsfiddle 链接,因为我是新来的吗?然后我可以给你看我的代码
  • 如果它说它需要跟随代码,只需将您的代码添加到小提琴链接旁边的问题中
  • 这是我所有的代码,请帮忙!!

标签: javascript margin


【解决方案1】:

您不需要逐像素添加。您可以直接从 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

【讨论】:

  • 非常欢迎您 :) 如果有帮助,请考虑接受我的回答。 (左边的绿色V)
  • jsfiddle 链接已损坏。请修复
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
相关资源
最近更新 更多