javascript - 如何在单个页面上创建滚动到顶部按钮?

标签 javascript jquery html

经过一段不错的搜索时间,我仍然没有找到有关此特定功能的任何信息,但我确信它可以完成。

我正在使用的网站虽然只有一个,但页面却很短。我为这个长页面创建了一个滚动到顶部按钮,没有任何问题。我希望此按钮仅适用于这个单独的页面,但是当我加载网站上的另一个页面时,我收到控制台错误 - '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/

相关文章:

javascript - 将 tailwind v2 升级到 v3 TypeError : Cannot read property

javascript - 使用 AJAX 从 JSON 文件调用数据

javascript - 选择所有编号大于 50 的元素项

css - 当我在里面有一个字段集时,div 高度不会扩展

javascript - Crossrider 扩展平台

javascript - 在 JavaScript 中将带小数的 float 解析为 JSON,也将 1 解析为 1.00

javascript - 使用 Bootstrap 的词缀时“跳过”

javascript - 从 char 到 char 的正则表达式选择由字符分隔的间隔

html - 如何在表格中换行同时具有不同的单元格宽度?

javascript - 如何将 Excel 列复制并粘贴到带有输入的 HTML 表格中?