zoukankan      html  css  js  c++  java
  • firefox浏览器兼容event事件方法

    firefox浏览器没有window.event对象,但是我们可以给函数的第一个参数传递个event来实现,但是总觉着不方便。搜索后发现有人实现了,觉着写的不错,以下是具体方法。

    自然,我们都习惯了 IE,在 IE 中要在函数中获得各事件对象很容易,直接用 event、event.srcElemtn、event.fromElement、event.toElement 就行了。在 FireFox 中获得触发事件的元素可以用 event.target,但其他两个 fromElement 和 toElement 就要费些周折。

    所以,为了保持一致的使用方式,也为了保持原有的使用习惯,我们加入以下 JS 代码(代码有些紧凑,未加注释,应该很好理解):

    <script language="javascript">
    if (window.addEventListener) {
      FixPrototypeForGecko();
    }
    function FixPrototypeForGecko() {
      HTMLElement.prototype.__defineGetter__("runtimeStyle", element_prototype_get_runtimeStyle);
      window.constructor.prototype.__defineGetter__("event", window_prototype_get_event);
      Event.prototype.__defineGetter__("srcElement", event_prototype_get_srcElement);
      Event.prototype.__defineGetter__("fromElement", element_prototype_get_fromElement);
      Event.prototype.__defineGetter__("toElement", element_prototype_get_toElement);
    }
    function element_prototype_get_runtimeStyle() {
      return this.style;
    }
    function window_prototype_get_event() {
      return SearchEvent();
    }
    function event_prototype_get_srcElement() {
      return this.target;
    }
    function element_prototype_get_fromElement() {
      var node;
      if (this.type == "mouseover") node = this.relatedTarget;
      else if (this.type == "mouseout") node = this.target;
      if (!node) return;
      while (node.nodeType != 1) node = node.parentNode;
      return node;
    }
    function element_prototype_get_toElement() {
      var node;
      if (this.type == "mouseout") node = this.relatedTarget;
      else if (this.type == "mouseover") node = this.target;
      if (!node) return;
      while (node.nodeType != 1) node = node.parentNode;
      return node;
    }
    function SearchEvent() {
      if (document.all) return window.event;
      func = SearchEvent.caller;
      while (func != null) {
        var arg0 = func.arguments[0];
        if (arg0 instanceof Event) {
          return arg0;
        }
        func = func.caller;
      }
      return null;
    }
    </script>

    好了,现在不管是在 IE 中还是在 FireFox 中,触发事件后都有了 event、event.srcElement、event.fromElement、event.toElement 属性了。这就来做个测试吧:

    <script>
    function test() {
      alert("event:" + event + ", srcElement:" + event.srcElement.innerHTML + ", fromElement:" + event.fromElement.innerHTML + ", toElement:" +   event.toElement.innerHTML)
    }
    </script>
    <button onmouseout="test()">MouseOut</button>
    <button onmouseover="test()">MouseOver</button>

    经个人测试,在火狐下完美运行,以后不用必须给函数的第一个参数传递event了。

  • 相关阅读:
    jquery 添加关键字小插件
    打印出所有每一位都与其他位不重复的自然数
    尾递归版,斐波那契数列
    如何在移动端宽度自适应实现正方型?
    css隐藏元素的六类13种方法
    如何给行内元素设置宽高?
    css实现垂直水平居中的方法
    pwa
    目录树生成工具treer
    服务端返回的json数据,导致前端报错的原因及解决方法
  • 原文地址:https://www.cnblogs.com/heaventear/p/2999430.html
Copyright © 2011-2022 走看看