how to prevent focus event in IE when mousedown happens

99封情书 提交于 2020-01-10 03:01:07

问题


event.preventDefault(); return false; event.stopPropagation();

any of them can prevent focus event from happening when I trigger a mousedown event in Firefox and chrome, but it failed in IE.In fact,chrome has another problem. when mousedowning, :hover css is not working. `

<input type="text" id="name">
<div id="suggest">
  <div>mark</div>
  <div>sam</div>
  <div>john</div>
</div>
$("#name").focus(suggest.show).blur(suggest.hide);

` what I expected is, when I click the sub div, such as "sam",and then $("#name").val("sam"). but the problem is, when I press the mouse(just mousedown,not released), the $("#name").blur runs immediately and suggest div becomes hide.


回答1:


Use :active instead of :hover for CSS to apply while the mouse button is down.

I don't think that preventing the blur event will do quite what you want, since if the user clicks on the input, then on the div, then elsewhere on the page, then the div will remain. I can think of a few different options, each with their own pitfalls. This one will behave correctly while the user remains within the page, but will leave the div showing if the user moves to the address bar:

$("html").on("focus", "#name", function() {
    $("#suggest").show();
}).mousedown(function() {
    $("#suggest").hide();
}).on("mousedown", "#name, #suggest", function(e) {
    e.stopPropagation();
});​

jsFiddle: http://jsfiddle.net/nbYnt/2/

If you don't need to support IE7, then you can do this using just CSS (and it works exactly as expected on any modern browser, including IE8):

#suggest {
    display: none;
}

#name:focus + #suggest, #suggest:focus {
    border: none;
    display: block;
}

Note that you need to put a tabindex on the div for the CSS method to work:

<div id="suggest" tabindex="-1">

jsFiddle: http://jsfiddle.net/nbYnt/1/

Finally, you can err on the side of having the div vanish by combining JavaScript with CSS (this works in IE7):

#suggest:hover {
    display: block !important;
}

$("#name").focus(function() {
    $("#suggest").show();
}).blur(function() {
    $("#suggest").hide();
});

The problem with this method is that after clicking on the div, simply moving the mouse away will cause the div to vanish.

jsFiddle: http://jsfiddle.net/nbYnt/4/




回答2:


You can use "unselectable" attribute for prevent losing focus in IE and mousedown handler for other.

<input type="text" id="name">

<div onmousedown="return false" unselectable="on" id="suggest">
  <div unselectable="on">mark</div>
  <div unselectable="on">sam</div>
  <div unselectable="on">john</div>
</div>


来源:https://stackoverflow.com/questions/9804280/how-to-prevent-focus-event-in-ie-when-mousedown-happens

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