经过一段不错的搜索时间,我仍然没有找到有关此特定功能的任何信息,但我确信它可以完成。
我正在使用的网站虽然只有一个,但页面却很短。我为这个长页面创建了一个滚动到顶部按钮,没有任何问题。我希望此按钮仅适用于这个单独的页面,但是当我加载网站上的另一个页面时,我收到控制台错误 - 'Uncaught TypeError: Cannot read property 'style' of null atscrollFunction'
这是我尝试用来检查页面的 href 的函数:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (window.location.href.indexOf("portfolio.html")) {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("scrollButton").style.display = "block";
} else {
document.getElementById("scrollButton").style.display = "none";
}
}
}
任何指导将不胜感激。
最佳答案
这与 Sujen K. 提出的答案类似,但有一些差异,可以简化代码清晰度并提高性能:
var elementExists = document.getElementById('scrollButton');
// We can skip the page URL check because in theory this
// behavior is desired on any page with the scrollButton
if (elementExists) {
// By moving the onScroll function into the if statement
// it no longer has to check on pages without scrollButton
// We can also simplify how it is set up.
window.onscroll = function () {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
// We can reuse elementExists here for a minor
// performance gain instead of having to get it again.
elementExists.style.display = "block";
} else {
elementExists.style.display = "none";
}
};
}
关于javascript - 如何在单个页面上创建滚动到顶部按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42682581/