首页 > 解决方案 > 单击绝对位置而不是后面的元素

问题描述

我有一个卡片列表,以及两个绝对定位的按钮。

我的卡

我有一个带有两个按钮的元素,我的垃圾桶图标上有一个 JS 事件。

CSS

.list > .choice {
    position: relative;
    margin: 5px 0;
    padding: 15px;
    cursor: pointer;
    background: rgb(254, 254, 254);
    border-radius: 7px;
    border: 1px solid rgb(229, 229, 229);
    transition: 0.3s;
}
.list > .choice:hover {
    background: rgb(245, 247, 248);
}

.list > .choice > .choice_badge {
    display: inline-block;
    vertical-align: baseline;
    width: 100px;
    height: 25px;
    margin-right: 10px;
    border-radius: 5px;
    border: 1px solid black;
    text-align: center;
}

.list > .choice > .choice_content {
    display: inline-block;
    vertical-align: middle;
}

.list > .choice > .choice_content > .choice_title {
    font-weight: bold;
}
.list > .choice > .choice_content > .choice_sub_title {
    font-size: 1.2rem; 
}
.list > .choice > .choice_options {
    position: absolute;
    top: 50%;
    right: 15px;
    transform: translateY(-50%);
    color: rgb(116 117 118);
}
.list > .choice > .choice_options > .material-icons {
    margin-left: 1.2rem;
    color: black;
    font-size: 2rem;
}
.list > .choice > .choice_options > .material-icons > a {
    color: black;
    text-decoration: none;
}

HTML

<div class="list">
    <div class="character choice" user_id="0">
        <div class="choice_content">
            <span class="choice_title">Lorem IPSUM</span>
            <br/>
            <span class="choice_sub_title">Lorem IPSUM</span>
        </div>
        <div class="choice_options">
            <span class="material-icons"><a href="#">create</a></span>
            <span class="material-icons delete">delete</span>
        </div>
    </div>
</div>

JS (jQuery)

$(document).ready(function(){
    $(document).on('click', '.choice', function(){
      alert('clicked on "choice" element');
    });
    
    $(document).on('click', '.delete', function () {
        alert('clicked on delete button');
    });
});

当我单击垃圾箱时,会打开一个弹出窗口,但是因为后面有 .choice 事件,所以弹出窗口打开并且导航器将页面更改为 mylink。

有人知道如何解决这个问题吗?谢谢。

标签: clickpositionabsolute

解决方案


我可以看到删除图标按钮位于 .choice 元素中。正如您所知,单击事件会影响元素及其子节点,因为如果单击元素或子节点,则会触发该事件。但是,从我的角度来看,修复很容易,您不需要t 需要两个事件。

$(document).ready(function(){
    $(document).on('click', '.choice', function(e){
         // check if clicked element is the delete button 
        if($(e.target).hasClass('delete')){
             // code for delete event   
             //--you could provide a method here to make this cleaner
             delete(e.target);
        } else {
             // code for choice element
             choice(e.target);
        }
     });
 });

 function delete(args){
     // code here
 }

为 .choice 元素及其子元素(.delete 元素)设置单独的事件是相当不必要的。至少我是这么认为的


推荐阅读