Button element not firing click event when clicking on button text and releasing off it (but still inside the button)?

烂漫一生 提交于 2019-12-21 01:09:09

问题


On WebKit browsers (I tested on Chrome and Safari on Mac), button element behaves weird:

Wen in this fiddle http://jsfiddle.net/5ReUn/3/ you do the following:

  1. Press left mouse button while the cursor is over HTML button text
  2. Move the cursor (while pressed) to an area of the button without text
  3. Release the mouse button

Then the click event on the button element is not fired!

HTML is very simple:

<button id="button">Click</button>

And the CSS is not sophisticated at all:

button {
    display: block;
    padding: 20px;
}

JS for click catching:

button = document.getElementById('button');
button.addEventListener('click', function() {
    console.log('click');
});

Many visitors to my site complain that buttons are not clickable. They don't realize they are moving the cursor while clicking.

Has anybody found a workaround for this?


回答1:


It turns out to be a bug in WebKit.

An quick non-JavaScript solution is to wrap the text in a SPAN element and make it click-through:

<button>
    <span>Click Me</span>
</button>

Example CSS:

span {
    display: block;
    padding: 20px;
    pointer-events: none;   // < --- Solution!
}

Since the bug appears only in WebKit, browsers that don't support pointer-events can be ignored.




回答2:


If you don't find another solution, you can use the mousedown event instead of the click event.

This is not the best solution since it behaves different than normal. Normally the user is expecting the action to happen when the finger is released from the mouse button. Not when the finger is holding the mouse button down.




回答3:


Here you are trying to drag instead of clicking it. So, you may want to try mousedown event instead.

//This is same as click event
var down = false;
var button = document.getElementById('button');
var info = document.getElementById('info')
button.addEventListener('mousedown', function() {
    down = true;  
});


button.addEventListener('mouseup', function() {
    if(down){
        info.innerHTML += "click ";
        down = false;
    }
});

jsfiddle




回答4:


You could add a div around the button (with like a margin of what, 20px?) with the same js/jquery bound to it. That way, if they would missclick(lol) the script would still fire. However, I noticed that indeed if you drag your mouse off the button while it's pressed, the button will not do anything (doesn't just happen on your page, i.e. try it with Facebook-login buttons or even the buttons on this website).



来源:https://stackoverflow.com/questions/15679787/button-element-not-firing-click-event-when-clicking-on-button-text-and-releasing

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