【问题标题】:Jquery animate not detecting scroll properlyJquery动画没有正确检测滚动
【发布时间】:2021-06-23 06:40:55
【问题描述】:

我正在尝试制作一个功能,让按钮向上滑动以在滚动后将您带回顶部。但是由于某种原因,它只是行不通。当我使用它时效果很好

        if (scroll >= 84) {
            $("#ID").fadeIn();
        } else {
            $("#ID").fadeOut();
        }

但是当它不适用于动画或 css 时。 我跟踪滚动的方式是使用事件监听器,并用值声明一个 let:

let scroll = this.scrollY;

我希望这些信息足以让您了解我的目标。提前感谢您的帮助

【问题讨论】:

  • 您是否在事件监听器内部声明并重置了变量?它不会自动“更新”。
  • 我对 javascript 和 jquery 还是很陌生,所以我不确定你所说的重置是什么意思?其余代码在事件监听器中
  • 在我的回答中,每次触发滚动事件侦听器时,我都会将scrollDistance 重置为window.scrollY。这相当于“重置”。

标签: javascript html jquery css jquery-animate


【解决方案1】:

试试这个(运行并向下滚动):

var timeout;

for (var i = 0; i < 200; i++) {
  document.body.innerHTML += "Example Text<br>"
}

window.addEventListener("scroll", () => {
  var scrollDistance = window.scrollY
  if (scrollDistance >= 100) {
    clearTimeout(timeout);
    document.querySelector("button").style.display = "";
    setTimeout(function() {
      document.querySelector("button").style.opacity = "1"
    }, 1);
    document.querySelector("button").style.cursor = "pointer";
  } else {
    clearTimeout(timeout);
    document.querySelector("button").style.opacity = "0";
    document.querySelector("button").style.cursor = "";
    timeout = setTimeout(function() {
      document.querySelector("button").style.display = "none"
    }, 500);
  }
})

document.querySelector("button").addEventListener("click", () => {
  window.scroll({
    top: 0,
    left: 0,
    behavior: 'smooth'
  });
})
button {
  position: fixed;
  right: 10px;
  bottom: 10px;
  border-radius: 50%;
  height: 50px;
  width: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffcccb;
  border: 2px solid black;
  opacity: 0;
  outline: none;
  transition: opacity 0.5s;
}

button>div {
  width: 20px;
  height: 20px;
  border-width: 5px 5px 0px 0px;
  border-style: solid;
  border-color: black;
  transform: translate(0, 4px) rotate(-45deg);
}
<button>
<div></div>
</button>

请注意,大部分代码只是设置。这是执行滚动工作的实际代码:

document.querySelector("button").addEventListener("click", () => {
  window.scroll({
    top: 0,
    left: 0,
    behavior: 'smooth'
  });
})

它只是监听按钮的点击,然后滚动到顶部。

【讨论】:

  • 很抱歉花了这么长时间才回答,但这很有效,非常感谢:)
  • 没问题!您会考虑将我的答案标记为正确吗?
猜你喜欢
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-08
相关资源
最近更新 更多