document.body.scrollTop Firefox 返回 0 :只有 JS [英] document.body.scrollTop Firefox returns 0 : ONLY JS
问题描述
纯 javascript 中的任何替代方案?
Any alternatives in pure javascript?
以下作品适用于歌剧、铬和野生动物园.尚未在资源管理器上进行测试:
The following works in opera, chrome and safari. Have not tested yet on explorer:
http://monkey-me.herokuapp.com
https://github.com/coolcatDev/monkey-me-heroku/blob/master/static/js/myscripts.js
在页面加载时应向下滚动到 div '.content':
At page load should scroll down to div '.content':
var destiny = document.getElementsByClassName('content');
var destinyY = destiny[0].offsetTop;
scrollTo(document.body, destinyY, 200);
function scrollTo(element, to, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 2;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
scrollTo(element, to, duration - 2);
}, 10);
};
推荐答案
尝试使用这个:document.documentElement.scrollTop
.如果我是正确的,document.body.scrollTop
已被弃用.
Try using this: document.documentElement.scrollTop
. If I am correct document.body.scrollTop
is deprecated.
更新
似乎 Chrome 不与答案一起玩,按照@Nikolai Mavrenkov 在评论中的建议安全使用:
Seems like Chrome does not play along with the answer, to be safe use as suggested by @Nikolai Mavrenkov in the comments:
window.pageYOffset ||document.documentElement.scrollTop ||document.body.scrollTop ||0
现在应该覆盖所有浏览器.
Now all browsers should be covered.
这篇关于document.body.scrollTop Firefox 返回 0 :只有 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!