问题
I have a page where I have to make the background be a clickable link, whilst having the foreground works okay. I managed to get the background clickable this way:
<div id="site_background_container" onclick="window.location.href='{{$background_link}}'" style="position:relative; z-index:-100; cursor:pointer;">
<div id="site_main_container" style="z-index:5;">
The problem is that now the site_main_container
div is also clickable. How can I limit the click-ability to only site_background_container
?
Thanks!!
回答1:
Use jQuery. If the e.target
is the same element as this, you've not clicked on a descendant.
$('#site_background_container').on('click', function(e) {
if (e.target !== this) {
return;
}
alert('clicked the site_background_container');
});
Have a look at the snippet below:
$('#site_background_container').on('click', function(e) {
if (e.target !== this) {
return;
}
alert('clicked the site_background_container');
});
#site_background_container {
background: #ff0;
padding: 20px;
}
#site_main_container {
background: red;
color: white;
padding: 10px;
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="site_background_container">
<div id="site_main_container" style="z-index:5;">
Site Main Container
</div>
</div>
Hope this helps!
来源:https://stackoverflow.com/questions/41000403/having-a-clickable-background-div-but-excluding-foreground-divs