Webkit <button onclick> does not fire in certain situations

断了今生、忘了曾经 提交于 2019-12-05 09:40:53

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.)

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/

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