Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

javascript - Prevent firing focus event when clicking on div

This question is similar to my previous question, Click action on Focused DIV, but this time the main topic is, How to prevent focus event from triggering when I click one of the divs. Last time I had one div with tabindex='-1' to make it focusable on click, now I have a list of divs with tabindex>0 so they can gain focus when tabbing as well.

<div tabindex='1'>Div one</div>
<div tabindex='1'>Div two</div>
<div tabindex='1'>Div tree</div>
<div tabindex='1'>Div four</div>

some styling:

div {
    height: 20px;
    width: 60%;
    border: solid 1px blue;
    text-align: center;
}
div:focus {
    border: solid 2px red;
    outline: none;
}

Now I'm using a flag(action) to fire an action(alert) when clicking the div for 2nd time, and with just one click if it's already focused,with TAB for example.

var action = false;
$('div')
    .click(function(e){
        e.stopImmediatePropagation();
        if(action){alert('action');}
        action = true;})
    .focus(function(){action = true;})
    .blur(function(){action = false;});

The problem with the code above is focus event is being fired, which means stopImmediatePropagation doesn't work the way I expected.. The two click action works commenting the focus event line, but you still need to double click when div gains focus on TAB. Here is the example: http://jsfiddle.net/3MTQK/1/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

DEMO here

I think you are missing some parts here,

  1. event.stopPropagation() is used to stop the event from bubbling. You can read about it here.

  2. event.stopImmediatePropagation() In addition to keeping any additional handlers on an element from being executed, this method also stops the bubbling by implicitly calling event.stopPropagation(). You can read about it here

  3. If you want to stop browser events, then you should use event.preventDefault(). You can read about it here

  4. click = mousedown + mouseup -> The focus will be set on a HTML element when the mouse down is successful. So instead of binding click event, you should use 'mousedown'. See my demo.

  5. You cannot use 1 action boolean value to determine which div is clicked and how many times it has been clicked. Check my Demo to see how you can handle that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...