I have a div
with a table, which each TD of this table will have an event onClick
.
But sometimes, I will need to show some texts in front of this table, eventhough, this text can not mess my table's TDs.
So my problem is, I need to show a text in front of a table, but when I click on this text, it will not affect anything, and the correct clicked TD behind the text should call its event.
I have #div1
and #div2
, #div1
is behind, #div2
is the front (both are position:absolute
).
So, #div1
is there, but it's invisible , only #div2
is shown.
Eventhough, only #div2
is being shown, I need to show the text from #div1
in front of #div2
. In order to make this, I put a span
on #div1
and set span's z-index:1
. This way, #div1
is still not appearing, but its span
is.
Everything is OK, but I got a new problem now.
I need to click on #div2
(the front), and get the event on the whole div.
Even if there is a text from #div1
, it shouldn't have bussiness there, just be showed.
It's hard to understand just reading, so I made this Fiddle .
Click on the red "Text1 from #div1...", I need it to alert the TD html content!
You can try this workaround: http://jsfiddle.net/W9jy5/5/
JavaScript
$(document).ready(function(){
$("#div2").click(function(){
clickedOnDiv2();
});
$('#span1').click(function (e) {
var div2 = $('#div2'),
offset = div2.offset();
if (e.pageX > offset.left && e.pageX < offset.left + div2.width() &&
e.pageY > offset.top && e.pageY < offset.top + div2.height()) {
clickedOnDiv2();
}
});
function clickedOnDiv2() {
alert('#div2');
}
})
In this workaround there's a click event listener on the span element. If the user click on Text1 and the click is over #div2 we execute clickOnDiv2
.
And here it answer for the question in your comment http://jsfiddle.net/W9jy5/17/ . It's cross-browser.
Since the #div1
and #div2
are DOM siblings, you can't "capture" the events of #div1
in #div2
. And since the SPAN
is a descendant to #div1
, but you still want the same handler as you attached to #div2
, you need to attach the listener on multiple elements or rearrange the DOM.
One way to solve this is to delegate the click to a parent div instead:
$("#container").on('click', '#div2, #div1 span', function(){
alert("#div2");
})
You can have the click "fall-through" the #div1 span1
with some CSS:
#div1 span{
pointer-events: none;
}
It should work in FF and webkit browsers, but you're out of luck with IE8 and lower.
Working example: http://jsfiddle.net/W9jy5/12/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.