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

时间:2018-12-19 16:38:19

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

1 个答案:

答案 0 :(得分:2)

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