简体   繁体   English

如何使用 css/js/anything 使 div 中的特定区域可点击

[英]How to make specific areas in a div clickable with css / js / anything

I'd like to show you an image of my page content so you'd understand what am I talking about:我想向您展示我的页面内容的图像,以便您了解我在说什么:

在此处输入图像描述

Now, I have two main divs on a page: the wrapper (the red one) and the purple :现在,我在一个页面上有两个主要的 div:包装器(红色的)紫色的:

<div id="purple" style="position:fixed; z-index:0; left:0; top:0; width:100%; height:100%; filter:alpha(opacity=50); opacity:0.5; cursor:pointer;" onclick="javascript:alert('purple clicked');"></div>
<div id="wrapper"></div>      

The wrapper contains many controls and other divs, and the purple is basically supposed to be clickable and perform some event, lets say alert('purple clicked');包装器包含许多控件和其他 div,紫色基本上应该是可点击的并执行一些事件,比如说alert('purple clicked');

The thing is that when I press inside the wrapper it also fires the purple event.问题是,当我按下包装器内部时,它也会触发紫色事件。 So what I did was to add the following code:所以我所做的是添加以下代码:

<script type="text/javascript">

    $("#purple").click(function (e) 
    {            
        window.event.cancelBubble = true;            
        e.stopPropagation();
    })

</script>

I understood that through this code I'll manage to click on the purple area and get the alert fire, the problem is that when I click inside the red area this alert is fired also - and this is not what I wanted!我了解到,通过这段代码,我将设法单击紫色区域并触发警报,问题是当我在红色区域内单击时,也会触发此警报 - 这不是我想要的!

So, eventually, if you haven't given up yet reading this post, here's the question:所以,最终,如果你还没有放弃阅读这篇文章,那么问题来了:

How to avoid the "purple events" fire when clicking the red zone?单击红色区域时如何避免“紫色事件”触发?

ps ps
I must have the purple div be like - this can't be changed:我必须让紫色 div 像 - 这不能改变:

width:100%;宽度:100%; height:100%高度:100%

There is no direct way to prevent bubbling down .没有直接的方法来防止bubbling down You have to use event.target.id to differentiate the purple div with others,您必须使用event.target.idpurple div与其他 div 区分开来,

Try this,尝试这个,

$("#purple").click(function(e){
  if(e.target.id == "purple")
  {
       alert("purple clicked.!");
  } 
});

DEMO演示

This should solve your problem:这应该可以解决您的问题:

CSS CSS

#wrapper
{
    z-index:1;
    margin: 0 -50px;
    left:50%;
    position:absolute;
}

Fiddle小提琴

You have a problem because your purple div overlays the red one, the reason for that is:你有一个问题,因为你的紫色 div 覆盖了红色的,原因是:

z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). z-index 仅适用于定位元素(位置:绝对、位置:相对或位置:固定)。

you should read more about it Z-index你应该阅读更多关于它的 Z-index

Note: Just realized your purple div does not encapsulate red/green divs.注意:刚刚意识到您的紫色 div 不封装红色/绿色 div。 This answer won't solve your problem in that case.在这种情况下,此答案不会解决您的问题。 It relies on the nested div structure as per the included example below.根据下面包含的示例,它依赖于嵌套的 div 结构。 I'll leave this answer in case someone else comes across it with a similar issue.如果其他人遇到类似问题,我会留下这个答案。 Maksym Stepanenko's answer below regarding z-index is the most correct one. Maksym Stepanenko 下面关于z-index的回答是最正确的。


There are two properties of the event object: currentTarget and target .事件对象有两个属性: currentTargettarget

  • currentTarget is the current element in the event bubbling phase. currentTarget是事件冒泡阶段的当前元素。
  • target is the element that is responsible for initiating the event. target是负责启动事件的元素。

Within the purple click event handler you could test to see if that element was the target in the event chain:purple单击事件处理程序中,您可以测试该元素是否是事件链中的目标:

$('#purple').click(function(e) {
    if ( e.currentTarget == e.target ) {
        console.log('clicked purple',Date.now());
    }
});
$('#red').click(function(e) {
    console.log('clicked red',Date.now());
});

This is helpful when:这在以下情况下很有帮助:

  • you don't want to constrain the event phasing to only the red object您不想将事件定相限制为仅红色对象
  • you don't want to have to remember to put e.stopPropagation in every click handler whose element is a child of #red / #purple您不必记住将e.stopPropagation放在每个元素是#red / #purple子元素的单击处理程序中

Here's a complete working example:这是一个完整的工作示例:

<!doctype html>
<html>
    <head>
        <title>Bubble Test</title>
        <style type="text/css">
            #purple {border:3px solid #3c1e40;background:#b459bf;}
            #red {margin:auto;width:958px;border:3px solid #400Aa0a;background:#ff2829;}
            .green {margin:20px;padding:30px;border:3px solid #1c401c;background:#54bf55;}
        </style>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#purple').click(function(e) {
                    if ( e.currentTarget == e.target ) {
                        console.log('clicked purple',Date.now());
                    }
                });
                $('#red').click(function(e) {
                    console.log('clicked red',Date.now());
                });
            });
        </script>
    </head>
    <body>
        <div id="purple">
            <div id="red">
                <p class="green">Hello World</p>
                <p class="green">Lorem ipsum dolor sit amet.</p>
            </div>
        </div>
    </body>
</html>

You could take this a step further and also compensate for #red :您可以更进一步,还可以补偿#red

$('#purple').click(function(e) {
    if ( e.currentTarget == e.target ) {
        console.log('clicked purple',Date.now());
    }
});
$('#red').click(function(e) {
    if ( e.currentTarget == e.target ) {
        console.log('clicked red',Date.now());
    }
});
$('.green').click(function(e) {
    console.log($(this).text(),Date.now());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM