当鼠标向下/向上添加/移除元素时,没有触发点击事件

Click event not emitted when mousedown/mouseup do add/removeClass on element

本文关键字:事件 元素 鼠标 添加      更新时间:2023-09-26

我将mousedown, mouseupclick处理程序附加到元素。在mousedown上,我向元素添加了一个类,在mouseup上,我删除了这个类,在click上,我做了一些工作。(这是对上下文的简化。在我的项目中,click事件由第三方组件处理。

我遇到的问题是, click事件从未在Safari和Firefox中发出,但它在Chrome中工作得很好。(我不知道IE是做什么的。我无权访问它,也不在乎它

代码如下:

HTML:

<div id="clickme">
    <div class="normal"></div>
    <div class="highlight"></div>
</div>
<input type="text" id="textinput"/>
CSS:

#clickme:not(.active) > .highlight {
    display: none;
}
#clickme.active > .normal {
    display: none;
}
.normal, .highlight {
    width: 100px;
    height: 100px;
}
.normal {
    background: blue;
}
.highlight {
    background: red;
}

JS:

var clickme = $('#clickme');
var textinput = $('#textinput');
clickme.on('mousedown', function(e) {
    clickme.addClass('active');
    // ^-- comment this out and the click event starts working
});
clickme.on('mouseup', function(e) {
    clickme.removeClass('active');
    // ^-- comment this out and the click event starts working after the second click
});
clickme.on('click', function(e) {
    e.preventDefault();
    textinput.val(Date.now());
});

JSFiddle: https://jsfiddle.net/xLskk3po/14/

JSFiddle没有JQuery: https://jsfiddle.net/xLskk3po/15/这表明这不是JQuery的问题

我偶然发现了这个问题:当一个鼠标下降和鼠标上升事件不等于点击,它看起来像我的问题是类似的。所以我做了一些愚蠢的事情:我在顶部放了一个透明的,绝对定位的元素。

HTML:

<div id="clickme">
    <div class="normal"></div>
    <div class="highlight"></div>
    <div class="abs"></div> <!-- this is the absolute element, covering #clickme -->
</div>
<input type="text" id="textinput"/>