Action on blur except when specific element clicked with jQuery

前端 未结 5 1094
旧时难觅i
旧时难觅i 2021-01-01 09:33

There are two elements in play:

$(\'#myInput\') // an input field for search
$(\'#myList\') // a list to display search results

I want to h

5条回答
  •  滥情空心
    2021-01-01 09:42

    Pigalev Pavel's answer above works great.

    However, If you want an even simplier solution, you can just "prevent default" in the "mousedown" of an element to prevent the blur event from taking place. (since preventing default actually means that in the end, the input never looses focus in the first place!)

    Of course, this is only if you're alright with preventing default in the div. It does have some side-effects, like the text is no longer selectable. As long as that's not an issue, this will work.

    I suppose if you hold the mouse down over the div, move the mouse outside of the div, and then release the mouse, it also doesn't fire the "blur" event. But in my case, I wasn't too worried about that either, since the click started in the target div.

    $("input").focus(function(){
    	$(this).val("");
    });
    
    $("input").blur(function(){
    	$(this).val("blur event fired!");
    });
    
    $("div").mousedown(function(e){
    	e.preventDefault();
    })
    div{
      height: 200px;
      width: 200px;
      background: blue;
    }
    
    
    
    Click here to prevent blur event!

提交回复
热议问题