可能你的 txt2imgSettings 元素不存在或者不可见,导致 scrollIntoView 方法不起作用。为了确保滚动效果正常,建议在调用 scrollIntoView 方法前,先检查 txt2imgSettings 元素是否存在,是否可见。

检查步骤:

  1. 元素是否存在: 使用 document.querySelectordocument.getElementById 检查 txt2imgSettings 是否存在。
  2. 元素是否可见: 使用 element.style.displayelement.offsetWidth 检查元素是否可见。

如果 txt2imgSettings 元素不存在或不可见,你可以尝试以下解决方案:

  • 使用 scrollTop 属性: 通过设置 document.body.scrollTopdocument.documentElement.scrollTop 属性实现滚动。
  • 使用第三方库: 一些 JavaScript 库提供更丰富的滚动功能,比如 SmoothScrollScrollReveal

代码示例:

function clicktxt2img() {
    // ...

    if (txt2imgSettings) { // 检查元素是否存在
        if (txt2imgSettings.style.display !== 'none' && txt2imgSettings.offsetWidth > 0) { // 检查元素是否可见
            txt2imgSettings.scrollIntoView({ behavior: 'smooth' });
        } else {
            // 使用其他方法实现滚动
            document.body.scrollTop = txt2imgSettings.offsetTop;
        }
    }

    // ...
}

通过以上步骤和解决方案,你可以有效解决 scrollIntoView 方法不起作用的问题,确保滚动功能正常运行。

JavaScript .scrollIntoView() 不起作用:原因及解决方法

原文地址: https://www.cveoy.top/t/topic/ogFZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录