简体   繁体   中英

Change menu option width with jQuery

I have got a menu on my homepage and on hover I would like them to enlarge. This is exactly what I have achieved, except there is one flaw:

When I move off before the animation ends, the option stops the animation and subtracts 30 from the width that left off from the previous animation. So it always intersects with the other animation and causes false results.

Example:

I move quickly to menu option 1, it only expands little - let's say by 10px - while I am on it, and as I move off the width decreases by 30px, which is more than the previously moved 10px, which results in a smaller button overall.

I would like to somehow capture how much it has moved during the mouseover animation and only decrease the width in the leaving function by that amount. Or, of course some other easy solution, if there is one...

Here's the code:

    $('.menu_option').hover(

        function() {

            var w = $(this).width()+30+"";
            $(this).stop().animate({ width:w}, 150, 'easeOutQuad');

        }, function() {

                var w = $(this).width()-30+"";
                $(this).stop().animate({ width:w}, 150, 'easeOutQuad');

        });

You need to complete the previous animation before the width is calculated

$('.menu_option').hover(function () {
    var $this = $(this).stop(true, true);
    var w = $this.width() + 30;

    $this.animate({
        width: w
    }, 150, 'easeOutQuad');
}, function () {
    var $this = $(this).stop(true, true);
    var w = $this.width() - 30 + "";

    $this.animate({
        width: w
    }, 150, 'easeOutQuad');
});

Demo: Fiddle

What you can do is make another variable which is the origin width then when you put it back go back to the origin:

js:

var o = $('.menu_option').width();
$('.menu_option').hover(function () {

    var w = $(this).width() + 30 + "";
    $(this).stop().animate({
        width: w
    }, 150, 'easeOutQuad');
}, function () {
    $(this).stop().animate({
        width: o
    }, 150, 'easeOutQuad');
});

http://jsfiddle.net/Hive7/qBLPa/6/

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