简体   繁体   English

JavaScript原型-对某些元素覆盖.scrollTo

[英]JavaScript Prototype - Override .scrollTo for certain elements

I am looking to effectively intercept any calls to .scrollTo and check whether the element is a certain one so that I can stop the browser from scrolling to that element. 我希望有效地拦截对.scrollTo的所有调用,并检查该元素是否为某个元素,以便可以阻止浏览器滚动到该元素。 The JavaScript file that runs the .scrollTo is out of my control, hence the need to intercept it. 运行.scrollTo的JavaScript文件不在我的控制范围内,因此需要对其进行拦截。

Here is the code I have so far: 这是我到目前为止的代码:

var oScrollTo = scrollTo;
HTMLElement.prototype.scrollTo = function(){
    var scrollId = this.id;
    if ( scrollId !== 'id-of-element') {
        console.log("yes");
        $(scrollId).oScrollTo();
    } else {
        console.log("no");
    }
};

It's basically a combination of this answer: https://stackoverflow.com/a/1740510 and this answer: https://stackoverflow.com/a/19209665 它基本上是以下答案的组合: https : //stackoverflow.com/a/1740510和此答案: https : //stackoverflow.com/a/19209665

Currently, it intercepts the .scrollTo call and logs "yes" if it's not the matching element and "no" it is. 当前,它拦截.scrollTo调用,如果不是匹配元素,则记录“是”,否则记录“否”。

However, it should still run .scrollTo in the normal way when "yes" is logged but it does not. 但是,在记录“是”但没有记录时,它仍应以常规方式运行.scrollTo。 Any ideas on how I can make that happen would be appreciated! 关于如何实现这一目标的任何想法将不胜感激! Thanks! 谢谢!

Your code is mostly right, but you are not attaching the orgScrollTo in the appropriate location to do what you are trying. 您的代码大部分是正确的,但是您没有将orgScrollTo附加到适当的位置来执行您尝试的操作。 Try something along these lines: 尝试以下方法:

HTMLElement.prototype.orgScrollTo = HTMLElement.prototype.scrollTo;
HTMLElement.prototype.scrollTo = function(){
    var scrollId = this.id;
    if ( scrollId !== 'id-of-element') {
        console.log("yes");
        this.orgScrollTo();
    } else {
        console.log("no");
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM