<!doctype html>
<html>
<head>
<title>demo</title>
<style type="text/css">
.main { position:relative}
#btn { border:none;cursor:pointer;background:#ccc }
.layer { position:absolute;height:30px;width:50px;background:#4cff00;display:none }
</style>
</head>
<body>
<div class="main">
<input id="btn" type="button" value="点击"/>
<div class="layer" id="layer">
</div>
</div>
</body>
<script>
function stopPropagation(e) {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = false;
}
}
var btn = document.getElementById("btn");
var layer = document.getElementById("layer");
btn.onclick = function () {
var e = window.event || arguments.callee.caller.arguments[0];
layer.style.display = "block";
layer.style.left = "10px";
layer.style.top = "50px";
stopPropagation(e);
}
window.onclick = function (e) {
layer.style.display = "none";
}
</script>
</html>
以上案例中,使用匿名函数, 传入 事件e,但是有时候我们 是普通函数 传不入匿名函数e。 怎么办:
var e = window.event || arguments.callee.caller.arguments[0];
stopPropagation(e);
手动获取到 事件, 然后让 stopPropagation 阻止冒泡。