Javascript > HTML 滚动按钮在页面顶部时不会消失

标签 javascript html css scroll

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

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()”中,它说当我向下滚动时,它应该使它出现,但是当我在顶部时,它应该消失,但它没有。有人知道为什么吗?

最佳答案

您需要默认设置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>

关于Javascript > HTML 滚动按钮在页面顶部时不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53855556/

相关文章:

PHP 表 - 如何在从数据库中提取的表的每一行上添加不同的超链接

javascript - Twitter 和 Facebook 分享网站分享按钮

css - -moz-transition 标题和文字移动不对称

css - 为什么我的 wordpress 主题没有背景图片?

javascript - 无法连接到 mongolab 数据库

javascript - Angularjs 在按钮单击时动态添加 li 元素

javascript - 如何在数组变量内运行函数数组

javascript - 两个 if 语句。两者都有效。仅印一张

javascript - 通过脚本将 Google 电子表格图表的 "Treat labels as text"值设置为 true

javascript - 清除现有对话框