首页 > 解决方案 > Jquery动画没有正确检测滚动

问题描述

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

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

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

let scroll = this.scrollY;

我希望这是足够的信息,可以让您了解我的目标。我在这里先向您的帮助表示感谢

标签: javascripthtmljquerycssjquery-animate

解决方案


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

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

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


推荐阅读