首页 > 解决方案 > scrollIntoView 不是函数 JS

问题描述

我的脚本应该在页面加载 2 秒后向下滚动到某个元素。它应该只在手机上工作。

window.HTMLElement.prototype.scrollIntoView = function() {};

if (window.innerWidth < 500) {
  setTimeout(function() {
    let toogleElement = document.getElementsByClassName('eapps-google-maps-bar-toggle');
    toogleElement.scrollIntoView({
      behavior: 'smooth'
    });
  }, 2000);
}
#padding { height: 1000px; }
<div id="padding"></div>
<div class="eapps-google-maps-bar-toggle" eapps-link="barToggle">Foo</div>

标签: javascripthtmljqueryfunctionscroll

解决方案


首先,您需要删除window.HTMLElement.prototype.scrollIntoView = function() {};,因为您不需要定义自己的功能。

其次,document.getElementsByClassName返回 HTML 集合,您可以使用toogleElement[0].

下面的例子

if (window.innerWidth < 2000) {
  setTimeout(function() {
    let toogleElement = document.getElementsByClassName('eapps-google-maps-bar-toggle');
    toogleElement[0].scrollIntoView({
      behavior: 'smooth'
    });
  }, 2000);
}
#padding { height: 1000px; }
<div id="padding"></div>
<div class="eapps-google-maps-bar-toggle" eapps-link="barToggle">Foo</div>


推荐阅读