admin管理员组

文章数量:1313599

Per the standards, I'm trying to use jQuery's on() method as much as possible for my event handlers. Instead of hover(), I tried using on('hover') but it does not work. What can I do to make this bit of code work with on() instead of hover()? Is there a list of events I can see that work with the on() method?

$(document).ready(function(){
    $('#navigation li').on('hover', function(){
        $(this).animate({
            paddingLeft: '+=15px'
        }, 200);
    }, function(){
        $(this).animate({
            paddingLeft: '-=15px'
        }, 200);
    });
});

Per the standards, I'm trying to use jQuery's on() method as much as possible for my event handlers. Instead of hover(), I tried using on('hover') but it does not work. What can I do to make this bit of code work with on() instead of hover()? Is there a list of events I can see that work with the on() method?

$(document).ready(function(){
    $('#navigation li').on('hover', function(){
        $(this).animate({
            paddingLeft: '+=15px'
        }, 200);
    }, function(){
        $(this).animate({
            paddingLeft: '-=15px'
        }, 200);
    });
});
Share Improve this question asked Jan 8, 2016 at 19:18 GTS JoeGTS Joe 4,19217 gold badges61 silver badges109 bronze badges 3
  • 2 well... hover isn't an event for starters. – Kevin B Commented Jan 8, 2016 at 19:19
  • As far as what events it supports, that is implemented by the browser. – Kevin B Commented Jan 8, 2016 at 19:20
  • 1 Incidentally, this could easily be replaced with pure CSS transitions. – Blazemonger Commented Jan 8, 2016 at 19:31
Add a ment  | 

3 Answers 3

Reset to default 6

$('div')
  .on('mouseenter', function(){ $(this).addClass('red'); })
  .on('mouseleave', function(){ $(this).removeClass('red'); });
div {
  min-height: 50px;
  border: 1px solid #000;
}

.red { background-color: #F00; }
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>

Well hover take two functions. On takes one.

$(document).ready(function(){
    $('#navigation li').on('mouseenter', function(){
        $(this).animate({
            paddingLeft: '+=15px'
        }, 200);
    });
    $('#navigation li').on('mouseleave', function(){
        $(this).animate({
            paddingLeft: '-=15px'
        }, 200);
    });
});

Well, I'm late to the party but I think this should do

$(document).ready(function(){
$('#navigation li').on('mouseover', function(){
    $(this).animate({
        paddingLeft: '+=15px'
    }, 200);
}, function(){
    $(this).animate({
        paddingLeft: '-=15px'
    }, 200);
});

});

本文标签: javascriptUsing jQuery on() Instead of hover()Stack Overflow