Jquery - Mouseover DIV = addClass
i build this really simple script but i did not work.
Can somebody tell me where the bug is?
HTML
<div id="hello" style="border: 1px solid #000000; margin:10px; padding:5px;">Hello</div>
<div style="border: 1px solid #000000; margin:10px; padding:5px;">Word</div>
<div style="margin:10px; padding:5px;">Test</div>
JS
$(function()
{
$('div').live('hover', function (event)
{
if (event.type == 'mouseover')
{
$(this).addClass('mark');
}
else
开发者_如何学运维 {
$(this).removeClass('mark');
}
});
});
http://www.jsfiddle.net/4pYth/4/
Thanks in advance!
PeterI think you want to use two separate live events for this one.
$('div').live('mouseenter', function() {
$(this).addClass('mark');
}).live('mouseleave', function() {
$(this).removeClass('mark');
)};
Edit:
Here is a link for the differences between mouseenter
and mouseover
, just in case you are curious:
What is the difference between the mouseover and mouseenter events?
hover
is not an event.
Many of the event-related shortcut methods on jQuery objects are actual events: click
, submit
, etc. But hover
is not, it's a separate shortcut method that registers a mouseenter
and a mouseleave
event.
live()
can only accept events, so if you want to use hover-like code with it you'll need separate events, as in Kyle's example.
However, this will be a little bit slow because now jQuery has to monitor every mouse movement to see if it is happening to/from a div
element. It may be faster to just use hover()
to bind the mouseenter
/leave
events on divs currently in the page, without live
-ness. If you do have dynamically-added div
elements that would mean having to rebind when adding them to the document though.
Better: just use CSS hover. It's only IE6 where good old :hover
fails; if you really need to provide nice hover effects to users of that browser (bah! they don't deserve it, the scoundrels!) then you can add fallback script for that browser only, eg.:
<style type="text/css">
div:hover, div.hover { background: red; }
</style>
<!--[if lt IE 7]><body class="browser-ie6"><![endif]-->
<!--[if gte IE 7]><!--><body><!--<![endif]-->
<script type="text/javascript">
if ($(document.body).hasClass('browser-ie6')) {
$('div').live('mouseenter', function() {
$(this).addClass('hover');
}).live('mouseleave', function() {
$(this).removeClass('hover');
)};
}
</script>
精彩评论