如果在使用IE 7或8时隐藏,则单击标签不选中复选框

Clicking on label not checking checkbox if hidden when using IE 7 or 8

本文关键字:标签 单击 复选框 隐藏 IE 8时 如果      更新时间:2023-11-03

我正在尝试使用与复选框元素关联的标签创建一个自定义设计的复选框,并隐藏(display:none)复选框。

这在除IE之外的所有浏览器中都可以正常工作,IE要求复选框可见才能点击标签。

这是我的密码。。。

HTML

<input type="checkbox" id="myCheck" />​

CSS

label.checkbox {
    border:1px solid #666;
    width:25px;
    height:23px;
    display:block; 
}​

jquery

$("input[type=checkbox]").each(function() {
    $(this).hide().before('<label for="' + $(this).attr("id") + '" class="checkbox"></label>');
});
$("input[type=checkbox]").live('change', function() {
    if ($(this).prop('checked') == true) {
        $('label[for=' + $(this).attr("id") + ']').html("X")
    } else {
        $('label[for=' + $(this).attr("id") + ']').html("")
    }
});​

或者jsfiddle

我不知道是否有更有效的方法来做到这一点,但你可以通过设置页面外的复选框元素位置来做到这

.hiddenEl {
   position:absolute;
   top: -3000px;
}

$("input[type=checkbox]").each(function() {
    $(this).addClass("hiddenEl").before('<label for="' + $(this).attr("id") + '" class="checkbox"></label>');
});

演示


更新

此外,您还可以将复选框的不透明度设置为零,这将在没有"dispayl:none"的情况下隐藏它,

$(this).css("opacity", 0)

$(this).fadeTo(0, 0)

试试这个:

#myCheck{
  position:absolute;
  left:-9999px;
  }

并保留复选框"可见"