我有以下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>
我希望这样做可以点击div B的位置不会调用它的onclick,但只有A是因为A是更高的z-index。
如果不是z-index,我该如何实现?
答案 0 :(得分:5)
您可以使用event delegation - 不需要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>
处理程序功能:
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;
答案 1 :(得分:2)
您的z-index不起作用,因为您需要将css位置更改为relative,fixed或absolute。 reference.sitepoint.com/css/z-index。
<div id="A" style="width:100px; height: 100px; background: green; padding: 15px;
z-index: 50; opacity: .5; position:relative;" onclick="alert('A'); return false;">
<div id="B" style="width:100%; height:100%; background: red; z-index:100;position:relative;"
onclick="window.event.stopPropogation();alert('B'); return false;" >
</div>
</div>
答案 2 :(得分:1)
我认为在你的风格中使用position:absolute并将一个定位在另一个上就可以做到这一点。目前div A和div B并排坐着。
答案 3 :(得分:0)
<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:event.preventDeafult();" >
</div>
</div>
根据您不希望B开火的情况,执行“preventDefault”。
答案 4 :(得分:0)
这是处理切换B的onclick事件的一种方法
示例:http://jsfiddle.net/pxfunc/cZtgV/
HTML:
<div id="A">A
<div id="B">B
</div>
</div>
<button id="toggle">Toggle B onclick</button>
JavaScript的:
var a = document.getElementById('A'),
b = document.getElementById('B'),
toggleButton = document.getElementById('toggle'),
hasOnClick = true;
a.onclick = function() { alert('hi from A') };
b.onclick = function() { alert('hi from B') };
toggleButton.onclick = function() {
if (hasOnClick) {
b.onclick = "";
} else {
b.onclick = function() { alert('hi from B') };
}
hasOnClick = !hasOnClick;
};
对于奖励积分,示例中有一个jQuery解决方案。