【问题标题】:scrollIntoView is not a function JSscrollIntoView 不是函数 JS
【发布时间】:2021-09-22 09:50:23
【问题描述】:

我的脚本应该在页面加载 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>

【问题讨论】:

  • 删除这个window.HTMLElement.prototype.scrollIntoView = function() {};再试一次?
  • 你的scrollIntoView() 函数没有做任何事情......?问题本身是因为getElementsByClassName 返回一个集合,而不是单个元素。您需要遍历所有这些,或者直接通过索引访问一个,例如。 toogleElement[0].scrollIntoView(...
  • @RoryMcCrossan 它删除了错误,但脚本没有滚动到元素(我现在没有控制台错误)
  • 对,因为你定义了函数,但它不包含实际执行滚动操作的逻辑。
  • 我遇到了这个错误stackoverflow.com/questions/53271193/…,这个问题的解决方案帮助了我,所以我做了空函数。我应该在里面写什么?

标签: javascript html jquery function scroll


【解决方案1】:

首先,您需要删除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>

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2017-07-15
    • 2016-06-19
    • 1970-01-01
    • 2018-05-11
    • 2021-03-14
    相关资源
    最近更新 更多