how to prevent blur() running when clicking a link in jQuery?

前端 未结 4 1376
死守一世寂寞
死守一世寂寞 2020-11-27 07:12

i have:


and

$(\'input\').blur(function(){
    alert(\'stay focused!\');
});

相关标签:
4条回答
  • 2020-11-27 07:17

    I had to solve this problem myself today, too. I found that the mousedown event fires before the blur event, so all you need to do is set a variable that indicates that a mousedown event occurred first, and then manage your blur event appropriately if so.

    var mousedownHappened = false;
    
    $('input').blur(function() {
        if(mousedownHappened) // cancel the blur event
        {
            alert('stay focused!');
            $('input').focus();
            mousedownHappened = false;
        }
        else   // blur event is okay
        {
            // Do stuff...
        }
    });
    
    $('a').mousedown(function() {
        mousedownHappened = true;
    });
    

    Hope this helps you!!

    0 讨论(0)
  • 2020-11-27 07:20

    Delay the blur a bit. If the viewer clicks a link to another page, the page should change before this code gets a chance to run:

    $('input').blur(function(){
        setTimeout(function() {alert('stay focused!');}, 1000);
    });
    

    You can experiment with what delay value for the timeout seems appropriate.

    0 讨论(0)
  • 2020-11-27 07:21

    If you want to keep the cursor at its position in a contenteditable element, simply:

    $('button').mousedown(function(){return false;});
    
    0 讨论(0)
  • 2020-11-27 07:29

    You can get this behavior by calling preventDefault() in the mousedown event of the control being clicked (that would otherwise take focus). For example:

    btn.addEventListener('mousedown', function (event) {
      event.preventDefault()
    })
    
    btn.addEventListener('click', function(ev) {
        input.value += '@'
        input.setSelectionRange(ta.value.length, ta.value.length)
    })
    

    See live example here.

    0 讨论(0)
提交回复
热议问题