Having a clickable background div but excluding foreground divs

天涯浪子 提交于 2019-12-23 17:58:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!