Webkit <button onclick> does not fire in certain situations

不羁的心 提交于 2019-12-07 06:45:34

问题


I noticed that in Webkit the <button> element does not fire the onclick event when the mouse is moved from/to child elements of the button during the click. With other words: when the mousedown and mouseup events do not happen on the same element - even if both are children of the button.

The same happens when clicking/releasing on/out of the pixels of the button text.

To clarify I made a testcase: http://jsfiddle.net/gx9B3/

It works fine in FireFox. Fails in Chrome 15 and QtWebkit 4.7.1

Is there a way around this? I need a solution specifically for Webkit because my project is targeted to this browser only.

Solution

I could solve this problem based on the method suggested by Jan Kuča (the solution I accepted). Some additional tweaks were necessary, especially introducing a timer to avoid double clicks. Have a look at my fully working solution at JSFiddle: http://jsfiddle.net/mwFQq/


回答1:


You could set up a mousedown listener on document.body (to fix the problem on the whole page). You would check if the mousedown event originated from an HTMLButtonElement (or from any of its child elements) and if it did, you set up a mouseup listener (on the button so it does not have to bubble too much) that will check the target property of the mouseup event. If it is contained in the button and is different from the target of the mousedown event, you fire a click event like this:

var e = document.createEvent('Events');
e.initEvent('click', true, true);
button.dispatchEvent(e);

(Do this only for WebKit-based browsers so that you don't get multiple click events in other browsers. Or you could call the preventDefault method of the mousedown event as it should also prevent firing the click event.)




回答2:


You could try adding this CSS style:

button * {
    pointer-events: none;
}

Child elements will then ignore mouse events and the click will come from the button element itself. Here's an example http://jsfiddle.net/Tetaxa/gx9B3/2/




回答3:


You can also solve it by pure CSS trick. Just place pseudo element over <button> to cover text:

button {
    position:relative;
    }
button:after {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    content:'';
    }


来源:https://stackoverflow.com/questions/7982213/webkit-button-onclick-does-not-fire-in-certain-situations

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