【问题标题】:Script not running in Firefox, but ran in Chrome脚本不在 Firefox 中运行,但在 Chrome 中运行
【发布时间】:2018-04-08 06:40:48
【问题描述】:

我编写了一个脚本来注册拇指滚轮事件(如果您想知道的话,可以使用 MX Master 2S)。但是,该脚本在 Chrome 中运行得非常好,但在 Firefox (Quantum) 中却没有。为什么会这样?

var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var elements = document.getElementsByClassName('pagination'); // get the elements
var search = (elements[0].innerHTML.match(regex));

//alert(search);
if(document.addEventListener){
    document.addEventListener("mousewheel", MouseWheelHandler, false);
    document.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
} else {
    document.attachEvent("onmousewheel", MouseWheelHandler);
}

function MouseWheelHandler(e) {
    var e = window.event || e;
  var ret = true;

  if (e.wheelDelta) {
    // Tilt to the left
    if (e.wheelDeltaX < 0) {
        str = window.location.toString();
        strsplit = str.split('/');
        preloc=Number(strsplit[4])+1;
        if (preloc > 0) {
        window.location.replace("https://somepage.com/page/"+preloc);}
        prelocstr=preloc.toString();
        if (prelocstr == "NaN") {
        window.location.replace(search[0]); }
      ret = false;
    }
    // Tilt to the right
    if (e.wheelDeltaX > 0) {
        str = window.location.toString();
        strsplit = str.split('/');
        preloc=Number(strsplit[4])-1;
        if (preloc > 0) {
        window.location.replace("https://somepage.com/page/"+preloc);}
      ret = false;
    }
  }

  event.returnValue = ret;
}

这个脚本是在 Tampermonkey 中编写的。谁能指出我的错误?提前致谢!

【问题讨论】:

标签: javascript google-chrome tampermonkey firefox-quantum firefox-57+


【解决方案1】:

处理鼠标滚轮事件的新标准是跨浏览器的标准:

https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent

https://developer.mozilla.org/en-US/docs/Web/Events/wheel

要使用此事件,请执行以下操作:

document.addEventListener("wheel", MouseWheelHandler);

而且没有必要:

e = window.event || e

活动将在那里。

【讨论】:

    【解决方案2】:

    只有 DOMMouseScroll 可与 Firefox 一起使用,但它使用不同的 API。因此,您必须为 Firefox 编写单独的处理程序,而不是使用 MouseWheelHandler,或者调整 MouseWheelHandler 以支持两者。

    正如kshetline 所指出的,现在有一个新标准适用于所有现代浏览器:https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent

    其他两个选项在 Firefox 中不起作用,如下所述:

    此功能是非标准的,不在标准轨道上。不要 在面向 Web 的生产站点上使用它:它不适用于每个人 用户。之间也可能存在很大的不兼容 未来的实现和行为可能会发生变化。

    来源:https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel

    【讨论】:

    • 真可惜。我想这没有其他选择吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2012-10-20
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多