兼容性问题JavaScript 工具方法集合

JavaScript 停止冒泡和阻止浏览器默认行为

2018-01-20  本文已影响3人  枫_d646

1. 事件兼容

function myfunc(e) { var evt = e ? e : window.event; } 

2. js 停止冒泡

function myfunc(e) {
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}

3. js 阻止默认行为

function myfunc(e) {
    window.event ? window.event.returnValue = false : e.preventDefault();
}

4. 说明

1. 防止冒泡: w3c 的方法是 e.stopPropagation(),IE则是使用e.cancelBubble = true
2. 阻止默认行为: w3c 的方法是 e.preventDefault(),IE 则是使用e.returnValue = false
3. return false : javascript 的 return false 只会阻止默认行为,而是用 jQuery 的话则既阻止默认行为又防止对象冒泡
 ### javascript 的 return false 只会阻止默认行为

<div id='div'  onclick='alert("div");'>
  <ul  onclick='alert("ul");'>
    <li id='ul-a' onclick='alert("li");'>
      <a href="http://caibaojian.com/"id="testB">caibaojian.com</a>
    </li>
  </ul>
</div>

<script>
  var a = document.getElementById("testB");
  a.onclick = function() {
      return false;
  };
</script>

### 使用 jQuery,既阻止默认行为又停止冒泡

<div id='div'  onclick='alert("div");'>
  <ul  onclick='alert("ul");'>
    <li id='ul-a' onclick='alert("li");'>
      <a href="http://caibaojian.com/"id="testC">caibaojian.com</a>
    </li>
  </ul>
</div>

$("#testC").on('click',function(){
  return false;
});

5. 总结使用办法

1. 停止冒泡行为
function stopBubble(e) { 
    //如果提供了事件对象,则这是一个非IE浏览器 
    if (e && e.stopPropagation) {
        //因此它支持W3C的stopPropagation()方法 
        e.stopPropagation(); 
    } else {
        //否则,我们需要使用IE的方式来取消事件冒泡 
        window.event.cancelBubble = true; 
    }
}
2. 阻止浏览器的默认行为
function stopDefault(e) { 
    //阻止默认浏览器动作(W3C) 
    if (e && e.preventDefault) {
        e.preventDefault(); 
    //IE中阻止函数器默认动作的方式 
    } else {
        window.event.returnValue = false; 
    }
    return false; 
}

6. 事件注意点

1. event 代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等;
2. event 对象只在事件发生的过程中才有效。
  1. firefox 里的 event 跟 IE 里的不同,IE 里的是全局变量,随时可用;
    firefox 里的要用参数引导才能用,是运行时的临时变量
  2. 在 IE/Opera 中是 window.event,在 Firefox 中是 event;
    而事件的对象,在IE中是 window.event.srcElement,在 Firefox 中是 event.target,Opera 中两者都可用
##下面两句效果相同:
function a(e) {
    var e = (e) ? e : ((window.event) ? window.event : null); 
    // firefox 下 window.event 为 null, IE 下 event 为 null
    var e = e || window.event; 
}

原文链接
上一篇 下一篇

猜你喜欢

热点阅读