简体   繁体   中英

jQuery conflicting hover/toggle states in IE?

Here's my code:

<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css">
    label {display:block; width:300px; height:20px;}
    label.selected{background-color:#a33;}
    label.hover{background-color:#ccc;}
</style>
</head>
<body>

<label>
    <input type="checkbox" />Test text
</label>


<script type="text/javascript">
$("label input").change(function(){ $("label").toggleClass("selected"); });
$("label").hover(function(){ 
    $("label").addClass("hover");
    }, function(){ 
    $("label").removeClass("hover"); 
});
</script>

</body>
</html>

Other than the obvious fact that my broad classnames and inline code aren't ideal (this is a quick extraction from a bigger chunk of code), I have another issue.

In IE7 and IE 6, when you hover over the label, the color changes as expected. However, when you select the checkbox and hover away, the color doesn't change to the 'selected' class's background color until you do something like click away in white space or another element on the page.

Go and unselect the checkbox, and the selected color is again residual until you click away. Adding a switch to toggleClass doesn't change the problem.

Of course this works as expected in modern browsers such as Chrome and FF. Any idea what is happening here?

IE doesn't fire the "change" event until the focus is lost on the element. Try binding to "click" instead of "change."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM