IE - hidden radio button not checked when the corresponding label is clicked
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I just noticed a strange behaviour in IE7.
I have radio buttons with associated labels as follows:
The radio button is hidden via css with display:none or visibility: hidden (don't ask)
The problem is - when I click the label in IE7 (haven't looked at other IE versions yet) the associated radio button is not actually checked. I confirmed this with jquery - the label click event is fired, but the radio button click event is not. A form post also confirms that the checked radio button does not change.
This works correctly in firefox, and also works correctly if I remove the CSS that hides the radio buttons.
Is this an IE bug or am I missing something?
回答1:
It probably is to do with the display: none - you may also find that hidden elements don't get their values submitted with the rest of the form. If you have control over it, you may want to try positioning the elements off screen rather then hiding them.
回答2:
This is a wiki answer to bring together all the different answers and options.
Option 1: Move the element off-screen as opposed to hiding it completely
position: absolute; top: -50px; left: -50px;
Option 2: Use a bit of JavaScript to set the radio button to checked when the label is clicked
Option 3: Set the element's width and/or opacity to zero
width: 0; /* and/or */ -moz-opacity:0; filter:alpha(opacity:0); opacity:0; outline:none; /* this prevents IE8 from having the line around it even though it's invisible */
Option 4: Use another browser :)
Basically, the spec for these things doesn't specifically state what behavior to use, but IE generally takes the stance that if it can't be seen, then it doesn't work. "Seen" and "work" can mean different things, but in this case it means that when display:none is set, the label doesn't activate the radio button, which leads to the usual workarounds necessary for so many things in IE.
回答3:
This works for me
width: 0px;
Tested in IE7 and IE8. Pure CSS no javascript.
回答4:
This issue exists in IE6, 7, 8, and even the current 9 beta. As a fix, positioning the radio button offscreen is a good idea.
Here's an alternative that doesn't have to involve the designer or the css: Hide the button normally, and make whatever function handles the click event for the button also handle the click event for the label.
I was using jQuery hide() function, so it wasn't easy to change the way an element is hide without writing a more complex code. I found this idea: I use class to store the checked attribute and set this attribute back again just before the submit.