javascript - 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>
解决方案
首先,您需要删除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>
推荐阅读
- python - 异步从网站上抓取链接?
- visual-c++ - 将 .dll 与 Bazel 链接时如何使用 .exp 文件?
- r - 根据其他变量中的顺序为新变量赋值
- amazon-web-services - 如何使用 CloudFormation 组织 ECS CodePipeline
- highcharts - 带有自定义数据的热图无法显示任何内容
- plugins - 更新 Capacitor 3 的自定义插件
- java - 使用选择器根据选中状态更改菜单项的颜色
- javascript - 使用 JavaScript 在 CSS 类中添加/删除属性
- r - 如何使数据集中的逗号分隔字符串变量成为 R 中的唯一行/列名称
- dart - 飞镖捕捉异常未来函数