首页 > 解决方案 > Javascript > HTML 滚动按钮在页面顶部时不会消失

问题描述

所以,我现在正在建立一个网站,并且我设置了一个按钮,当你向下滚动一小段距离时它应该会出现,当你点击它时,它会将你带到页面顶部。但是由于某种原因,该按钮始终可见,即使我在顶部,这是我的代码:

document.getElementById("scrollButton").onclick = goToTop();

window.onscroll = function() {
  "use strict";
  scrollFunction();
};

function scrollFunction() {
  "use strict";
  if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) {
    document.getElementById("scrollButton").style.display = "block";
  } else {
    document.getElementById("scrollButton").style.display = "none";
  }
}

function goToTop() {
  "use strict";
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
.scrollButton {
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 18px;
  border: none;
  outline: none;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

.scrollButton:hover {
  background-color: #555;
}

#fill {
  height: 150vh
}
<div id='fill'></div>
<button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button>

我不确定什么是错的,在javascript中的“scrollFunction()”上,它说当我向下滚动时,它应该让它出现,但是当我在顶部时,它应该消失,但它没有。有谁知道为什么?

标签: javascripthtmlcssscroll

解决方案


您需要display:none默认设置。

document.addEventListener('DOMContentLoaded', function() {
  scrollFunction();
})

document.getElementById("scrollButton").onclick = goToTop;

window.onscroll = function() {
  "use strict";
  scrollFunction();
};

function scrollFunction() {
  "use strict";
  if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) {
    document.getElementById("scrollButton").style.display = "block";
  } else {
    document.getElementById("scrollButton").style.display = "none";
  }
}

function goToTop() {
  "use strict";
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
.scrollButton {
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 18px;
  border: none;
  outline: none;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

.scrollButton:hover {
  background-color: #555;
}

#fill {
  height: 150vh
}
<div id='fill'></div>
<button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button>


推荐阅读