[英]JavaScript window.scrollTo Alternative
I'm writing a specific javascript plugin for a specific website. 我正在为特定网站编写特定的javascript插件。
In one of my methods i want to use window.scrollTo
but unfortunately the site owner has overridden the native functionality of this function (also window.scroll). 在我的一种方法中,我想使用
window.scrollTo
但是不幸的是,网站所有者已覆盖了此功能的本机功能(也包括window.scroll)。
So i'm thinking about 2 possible solutions: 所以我在考虑2种可能的解决方案:
myScrollTo
implementation myScrollTo
实现 If you have any ideas on this, i will be very glad to hear them :) 如果您对此有任何想法,我会很高兴听到他们的意见:)
Thanks. 谢谢。
Well you can create an iframe and use its window instance to get the native implementation of scrollTo
. 好了,您可以创建一个iframe并使用其窗口实例来获取
scrollTo
的本机实现。 The following code should work 下面的代码应该工作
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
window.altScrollTo = iframe.contentWindow.scrollTo;
Now you should be able to use it as below 现在您应该可以如下使用它了
aScrollTo.call(window, 0, 600)
Well it's not the perfect solutions but is suites my current needs. 好吧,这不是完美的解决方案,而是适合我当前的需求。
First i will check if the native function is overridden with this helpful piece of code : 首先,我将检查此有用的代码是否覆盖了本机函数:
function isFuncNative(f) {
return !!f && (typeof f).toLowerCase() == 'function'
&& (f === Function.prototype
|| /^\s*function\s*(\b[a-z$_][a-z0-9$_]*\b)*\s*\((|([a-z$_][a-z0-9$_]*)(\s*,[a-z$_][a-z0-9$_]*)*)\)\s*{\s*\[native code\]\s*}\s*$/i.test(String(f)));
}
Source: https://stackoverflow.com/a/7536972/3009194 资料来源: https : //stackoverflow.com/a/7536972/3009194
Then i will try the alternatives : window.scroll
as the is no difference between window.scroll() and window.scrollTo() 然后,我将尝试替代方法:
window.scroll
因为window.scroll()和window.scrollTo()之间没有区别
And finally if this one is also overridden, i guess i will use document.body.scrollTop
最后,如果这个也被覆盖,我想我将使用
document.body.scrollTop
Yes i know, there is a possibility that the body is not the scrolling Element. 是的,我知道,主体可能不是滚动元素。 Unfortunately the
document.scrollingElement
is still a draft and not supported in most browsers. 不幸的是
document.scrollingElement
仍然是草稿,大多数浏览器都不支持。
So the final code will look something like this: 因此,最终代码将如下所示:
function myScroll(left, top) {
if (isFuncNative(window.scrollTo)) {
window.scrollTo(left, top);
} else if (isFuncNative(window.scroll)) {
window.scroll(left, top);
} else {
document.body.scrollLeft = left;
document.body.scrollTop = top;
}
}
myScroll(0,150);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.