nodebook/20190925/20190925.md
2019-10-13 14:11:30 +08:00

1.0 KiB
Raw Permalink Blame History

20190925

js

  • 给任意元素添加监听器封装函数
  function addEventListener(ele,type,fn) {
    if(ele.addEventListener) {
      ele.addEventListener(type,fn,false)
    } else if (ele.attachEvent) {
      ele.attachEvent('on' + type, fn)
    } else {
      ele['on' + type] = fn
    }
  }

  • 给任意事件解绑监听器封装函数
  //如需解绑监听器,则添加事件必须为命名函数
  function removeEventListener(ele, type, fn) {
    if(ele.removeEventListener) {
      ele.removeEVentListener(type, fn, false)
    } else if (ele.detachEvent) {
      ele.detachEvent('on' + type, fn)
    } else {
      ele['on' + type] = fn
    }
  }

  • 阻止事件冒泡
//e | window.event 事件参数对象前者是w3c后者IE

//google,ie8 |  firefox不支持
//火狐不支持 window.event
window.event.cancelBubble = true;
e.cancelBubble = true;

//w3c firefox,google  | ie8不支持
e.stopPropagation();