【问题标题】:The element doesn't change color when scrolling back on top the page回到页面顶部时元素不会改变颜色
【发布时间】:2021-03-31 12:36:39
【问题描述】:

here's a fiddle 我想在滚动导航栏后更改页面上“@”元素的颜色。

它有效,但只有当我向下滚动时。

当我在页面顶部滚动时,它不起作用。因此,@ 在预期为白色时保持红色。

window.addEventListener("scroll", (event) => {
    if (!document.querySelector('.container')) return;
    let container = document.querySelector('.container');

    if (container.scrollHeight - container.scrollTop === container.clientHeight) {
        document.querySelector('.chat-icon').style.color = "red";
    } else
        document.querySelector('.chat-icon').style.color = "white";
});

附:白色元素是“容器”类之一,紫色是导航栏。

【问题讨论】:

  • 你在用 reactJS 吗?
  • 您的代码看起来不错。介意在 jsfiddle 或其他地方提供一个简单的例子吗?会更容易看到它的实际效果(包括你的标记顺便说一句)。
  • @Aer0 您现在可以看一个示例(问题中提供了链接)。

标签: javascript html css


【解决方案1】:

那是因为 div 无法滚动,变量 container.scrollTop 返回 0 mozzila docs

如果元素不能滚动(例如它没有溢出或者如果元素具有“不可滚动”的属性),scrollTop 为 0。

你可以使用 window.scrollY

window.addEventListener("scroll", (event) => {
let container = document.querySelector('.nav');
if (container.scrollHeight - window.scrollY === container.clientHeight) {
    document.querySelector('.chat-icon').style.color = "red";
} else
    document.querySelector('.chat-icon').style.color = "white";
});

here's a working a example

【讨论】:

  • 谢谢!这绝对是一个原因。现在它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 2020-02-19
  • 2021-06-09
  • 2020-06-13
  • 2015-12-30
  • 2015-04-29
相关资源
最近更新 更多