当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - IE - Prevent focus (click, doubleclick) on a select box if it has a specific class

问题描述:

I'm using javascript to simulate a disabled select element. I can't actually disable it as the .net validators fail, but that's another story.

I have the following function:

function preventFocus(e) {

if ($(this).hasClass("disabled")) {

e.preventDefault();

this.blur();

}

}

That is called here:

$("#ProvinceID").toggleClass("disabled").bind('focus click dblclick', preventFocus);

Double-clicking the select box in IE still seems to allow the items to be displayed and selected. I tried the IE developer toolbar, and the e.type is showing up as focus and dblclick. Is this an IE bug, or do I need to catch some other event? I also tried focusin.

Thanks!

网友答案:

This is 4 years late but I just discovered there is in fact a way to get IE ≤ 8 to do what e.preventDefault() on mousedown does in other browsers (which prevents selection and prevents focus): set the unselectable attribute! http://jsbin.com/yagekiji/1

Note that unlike the workarounds always suggested, which always boil down to setTimeout(function() { thingIDidntWantFocusStolenFrom.focus(); }), this prevents focus from ever being stolen by the mousedown target in the first place!

What's funny about unselectable is that it isn't inherited, so it's often overlooked in favor of the selectstart event (which bubbles, and e.preventDefault() on which prevents selection but doesn't prevent focus), or set on every descendant element with a tree-traversal (like the StackOverflow answer that first clued me in that this might be possible, or Tim Down's series of nearly identical answers), but you can actually just set it on event.target on mousedown.

(Also, jQuery ticket: http://bugs.jquery.com/ticket/10345)

网友答案:

I don't know if it's just a typo, but you should use e.preventDefault(); looks like you were missing the parenthesis.

分享给朋友:
您可能感兴趣的文章:
随机阅读: