实际上,我想创建一个没有jQuery的“Scroll to the top”按钮。“转到顶部”功能已在工作。现在我需要在用户向下滚动页面时自动执行display: nonedisplay: block。当它回到顶端的时候。

<a href="#ancor-top" id="GoTop">Top</a>

#GoTop {
    display: none;
    position: fixed;
    bottom: 20px;
    right: 30px;
    z-index: 99;
    border: none;
    outline: none;
    background-color: red;
    color: white;
    cursor: pointer;
    padding: 15px;
    border-radius: 10px;
}

最佳答案

试试这个

var goTop = document.getElementById('GoTop');
window.onscroll = function(ev) {
  if (this.pageYOffset > 100) {
    goTop.style.display = 'block';
  } else {
    goTop.style.display = 'none';
  }
};

div {
  height: 200vh;
  width: 100%;
}

#GoTop {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  border: none;
  outline: none;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 10px;
}

<a href="#ancor-top" id="GoTop">Top</a>
<div>
</div>

10-07 17:32