HTML button does not click even when is focused and the CSS rules kick in

亡梦爱人 提交于 2020-01-24 11:15:53

问题


Take a look at this button: http://jsfiddle.net/vtortola/Dnxpe/

I Chrome, if you click on the top border, even when the ":hover" and ":active" css rules triggers, the event is not triggered. If you click more in the center, then it works fine.

In IE9, if you do the same it miss the 50% of the clicks.

The problem are the margins, when you click the margins switch, giving the effect of the button being pushed, but this makes the pointer be out of the button if you are clicking the top border but... the event should be already triggered.... why this happen?

Thanks.


回答1:


This probably happens because a click() is considered complete only once both mousedown() and mouseup() are completed in succession. In the case of clicking near the top border mouseup() never gets triggered and the same holds true for click().

If you use mousedown() it'll work every time, but it'll happen before the entire click is completed.

$('button').mousedown(function(e){
    $('#clicks').append('<span>click </span>');
});

To solve this you could do the following:

Add a container to the button and then add a mousedown handler to the button and a mouseup handler to the container. If you make sure they were both invoked, then you can be sure that a click event on the button has been performed.

Like so:

HTML

<div id="cont"><button>Click me</button></div>
<div id="clicks">
</div>​​​​​​​​

JavaScript

var mdown = false;

$('button').mousedown(function(e){
    mdown = true;
});

$('#cont').mouseup(function(e){
    if (mdown)
    {
        $('#clicks').append('<span>click </span>');
        mdown = false;
    }
});

​



回答2:


I checked out you code and find an interesting bug.Its because of CSS. Even you can regenerate that bug.

Steps: 1. Click on button near top border but do not release your finger from mouse. 2. Now, look at the button,your button is actually pushed down and that's why,it does not able to fire button click event.

Solution:

Remove margin when button is active.

button:active,input[type=submit]:active
{
   box-shadow: 0px 0px 3px 3px #D8F6CE;
}

I hope it helps.




回答3:


Here's the solution I came up with that uses a css psudo element to capture the click event. The benefit here is that you don't need javascript. The click events are always captured by the :after and bubble up to the button.

http://jsfiddle.net/kevinrockwood/fUuUB/1/

The main thing to note is the css:

button:after{
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}


来源:https://stackoverflow.com/questions/11468780/html-button-does-not-click-even-when-is-focused-and-the-css-rules-kick-in

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