【问题标题】:JQuery animating borderJQuery 动画边框
【发布时间】:2012-04-28 02:23:04
【问题描述】:

我有这个 html 代码

<nav id="mainNav">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>        
    </ul>
</nav>

它有这个的css样式

    #mainNav { display:block; padding:5px; }
    #mainNav ul { display:block; list-style-type:none; width:500px; border-collapse:collapse; }
    #mainNav li { display:inline-block; width:100px; height:66px; text-align:center; padding-top:10px; float:left; background-color:gray; cursor:pointer; border-bottom:0px solid red; }
    #mainNav a { color:white; text-decoration:none; text-transform:capitalize; }
    #mainNav a.aHover { color:red; }

附在上面的是JQuery代码

$(document).ready(function() {
$('#mainNav li').mouseover(function() {
    var el = $(this);
    $(this).animate({
    "border-bottom-width":"+=5px"
    },{ queue: false, duration: 500 }, function() {
    el.css('border-bottom-width', '5px');   
    });
    $(this).children('a').addClass('aHover');
});
$('#mainNav li').mouseout(function() {
    var el = $(this);
    $(this).animate({
    "border-bottom-width":"-=5px"
    },{ queue: false, duration: 500 }, function() {
    el.css('border-bottom-width', '0px');   
    });
    $(this).children('a').removeClass('aHover');
});
});

现在我想要它做的是将边框颜色淡化为红色并将其淡出,或者如代码中所写,在悬停时将边框扩展至最大 5px,然后将边框放气回 0px。

问题是,如您所见,我尝试在动画结束时更改 LI 元素的类,以确保边框达到其最大或最小宽度,但这不起作用,为什么?

你将如何淡入和淡出边框颜色?

【问题讨论】:

  • "border-bottom-width":"+=5px",不应该有px。让它"border-bottom-width": "+=5"
  • 你可能想使用 mouseenter 和 mouseleave,或者 hoverIntent 插件。

标签: javascript jquery html css


【解决方案1】:

试试下面,

DEMO

$(document).ready(function() {
    $('#mainNav li').hover(function() {
        var el = $(this);
        $(this).stop(true, true).animate({
            "border-bottom-width": "5px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).children('a').addClass('aHover');
    }, function() {
        var el = $(this);
        $(this).stop(true, true).animate({
            "border-bottom-width": "0px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).children('a').removeClass('aHover');
    });
});

改变了,

  1. mouseover 事件到 mouseenter 因为它更适合您的情况
  2. mouseenter/mouseleave 更改为hover
  3. +=5px-=5px 更改为5px0px
  4. 添加了.stop(true, true) 以确保动画完成并清除队列。

【讨论】:

  • 好极了,现在当您将鼠标悬停在 LI 元素中的 a 标签上时,它认为鼠标在左,那么如何在将鼠标悬停在 a 标签上时保持边框?
猜你喜欢
  • 1970-01-01
  • 2011-09-12
  • 2012-04-04
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多