Mat*_*att 2 html javascript z-index
我有以下HTML代码:
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<div id="A" style="width:100px; height: 100px; background: #00FF00; padding: 15px;
z-index: 50; opacity: .5" onclick="javascript:alert('A')">
<div id="B" style="width:50px; height: 50px; background: #FF0000; z-index:10;"
onclick="javascript:alert('B')" >
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我希望这样做可以让点击div B的位置不会调用它的onclick,但只有A,因为A是一个更高的z-index.
如果没有z-index,我该如何实现呢?
您可以使用事件委托 - 不需要z索引等.将一(1)个点击处理程序分配给最顶层的div,并在处理程序中使用事件target/srcElement来决定与原始元素做什么(不).就像是:
<div id="A" style="width:100px; height: 100px;
background: #00FF00; padding: 15px;
z-index: 50; opacity: .5"">
<div id="B" style="width:50px; height: 50px;
background: #FF0000; z-index:10;" ></div>
</div>
Run Code Online (Sandbox Code Playgroud)
处理函数:
function myHandler(e){
e = e || event;
var el = e.srcElement || e.target;
// no action for #B
if (el.id && /b/i.test(el.id)){ return true; }
alert(el.id || 'no id found');
}
// handler assignment (note: inline handler removed from html)
document.querySelector('#A').onclick = myHandler;
Run Code Online (Sandbox Code Playgroud)