在 Fireofx 和 IE 中,要获取 scrollTop,您需要从 html 中获取它,而在 chrome 中,您需要从 body 元素中获取它。
有没有一种方法可以在没有浏览器嗅探的情况下检测到它?
var html = document.querySelector('html');
var body = document.querySelector('body');
var input = document.querySelector('input');
window.addEventListener('scroll', function() {
input.value = html.scrollTop + ' ' + body.scrollTop;
});
body {
height: 1000px;
}
input {
position: fixed;
top: 10px;
}
<input/>
我需要检测要滚动的元素,因为我需要从我的代码中更改 scrollTop。
最佳答案
如果生活很简单,您可以使用此事件处理程序属性。但是 I.E 在没有浏览器支持的情况下在作品中抛出一个 Spanner 。如果 IE 不可用,您当然可以随时编写一些代码来绕过 IE。
if (!('scrollingElement' in document)) (function() {
alert('IE is a pain in the arse');
}
window.addEventListener('scroll', function(event) {
alert(event.scrollingElement);
});
关于javascript - 如何检测需要滚动的元素主体或html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42097322/