最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clicking on label not checking checkbox if hidden when using IE 7 or 8 - Stack Overflow

programmeradmin3浏览0评论

I am trying to create a custom designed checkbox using the label associated to a checkbox element and hiding (display:none) the checkbox.

This works fine in all browsers except IE, which requires the checkbox to be visible for the label to be clickable.

Here's my code...

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("")
    }
});​

Or jsfiddle

I am trying to create a custom designed checkbox using the label associated to a checkbox element and hiding (display:none) the checkbox.

This works fine in all browsers except IE, which requires the checkbox to be visible for the label to be clickable.

Here's my code...

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("")
    }
});​

Or jsfiddle

Share Improve this question edited Jul 18, 2012 at 14:03 Tom asked Jul 18, 2012 at 13:52 TomTom 13k50 gold badges153 silver badges247 bronze badges 2
  • I think this happens in Firefox too, but I'm not sure. – Inkbug Commented Jul 18, 2012 at 14:06
  • Not in the latest version of FF on OSX, not tried on windows though. – Tom Commented Jul 18, 2012 at 14:16
Add a ment  | 

2 Answers 2

Reset to default 9

I don't know whether there is a more efective way to do this, but you can do this by setting checkbox element position out of the page,

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


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

DEMO


UPDATE

And also you can set checbox opacity to zero, that will hide it without "dispayl:none",

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

or

$(this).fadeTo(0, 0)

try this:

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

And leave the check box "visible"

发布评论

评论列表(0)

  1. 暂无评论