1

I have a ul for a menu:

<ul>
    <li class="one"><a href="#">Link One</a></li>
    <li class="two"><a href="#">And Two</a></li>
    <li class="three"><a href="#">Then it's Three</a></li>
    <li class="four"><a href="#">Finally Four</a></li>
<ul>

When I hover over the anchors, I want a background to slide in from the left, and back out when I move the mouse away again, while the position of the text remains static. I could probably make this work easily with background images, but I thought I might be able to do it by setting the width on the li to 0 and the a to some set width, then with jQuery animate the width of the parent li on the mouseover and mouseout.

$('a').mouseover(function(){
    $(this).parent().stop().animate({
        width: 270
    }, 200);
});
$('a').mouseout(function(){
    $(this).parent().stop().animate({
        width: 0
    }, 200);
});

When I just set the widths or set it via css, it works fine, but the slide in effect causes strange results: http://jsfiddle.net/LeonardChallis/D67dM/

My question is this: What do I need to change to make this work properly, or is there a better way to do it altogether? I don't necessarily mind the background image method, but preferably only if you can tell me why it's best and/or why other methods are worse.

4

1 回答 1

1

我发现我可以通过改变一些事情来实现这个结果。我现在有一个mouseenteron the a,而不是 a mouseouton the a,我将它更改为mouseleaveon the li。我也设置aposition: fixed;.

$('a').mouseenter(function(){
    console.log('mouseenter');
    $(this).parent().stop().animate({
        width: 270
    }, 200);
});
$('li').mouseleave(function(){
    console.log('mouseleave');
    $(this).stop().animate({
        width: 0
    }, 200);
});

更新的小提琴显示它工作得很好。

于 2013-07-19T08:11:26.203 回答