javascript - JQuery 动画边框

标签 javascript jquery html css

我有这个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');
});
});

现在我想让它做的是,将边框颜色淡入红色然后淡出,或者如代码中所写,在悬停时将边框扩展到最大 5 像素,然后将边框缩小回 0 像素。

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

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

最佳答案

试试下面,

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) 以确保动画完成并清除队列。

关于javascript - JQuery 动画边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10355516/

相关文章:

javascript - 从action发送的数据没有被reducer接收到

javascript - Twitter Bootstrap Typeahead gon gem 并将数据从模型传递到 JS - 以 json 格式

javascript - 如何通过javascript在html输入字段中放置度数符号

html - 对齐适用于 fiddle ,但运行时不适用于实际浏览器

html - 我可以指定一个文本框的位置并在没有顶部的情况下将其向下移动吗

html - 上传后,我的页面引用了不正确的文件夹

javascript - 如何使用 javascript 修复图像路径上的工具提示 "text on hover"

Netbeans 上的 JavaScript 稀缺代码支持功能

javascript - 使用 Sequelize 在多个表之间创建 "Many to Many"关系

javascript - 如何同时打印多个网页?