开发者

jQuery possible bloated code

开发者 https://www.devze.com 2023-03-24 20:41 出处:网络
I was throwing together an animated navbar with jQuery and it seems like a lot of js for what I am trying to accomplish, anyone know of a more elegant solution for this effect?

I was throwing together an animated navbar with jQuery and it seems like a lot of js for what I am trying to accomplish, anyone know of a more elegant solution for this effect?

Live Site:

http://daveywhitney.com/nav/2/

jQuery

$(document).ready(functio开发者_开发百科n() {

    $("#topnav li").prepend("<span></span>"); 

    $("#topnav li").each(function() { 
        var linkText = $(this).find("a").html(); 
        $(this).find("span").show().html(linkText); 
    }); 

    $("#topnav li").hover(function() {  
        $(this).find("span").stop().animate({
            marginTop: "-45" 
        }, 250);
    } , function() { 
        $(this).find("span").stop().animate({
            marginTop: "0"  
        }, 250);
    });

}); 


Just do it in CSS using image sprites and background-position. That would cut out all the jQuery.


I don't find your code complicated or un-elegant at all.
However, if you want a different approach, you can try css3 animations.
Here is a live example of your effect with no js at all.
Hope it helps.


you can skip 1 loop :

 $(document).ready(function() {

    $("#topnav li").html(function(){
        var $obj= $(this);
        $obj.prepend('<span>'+$obj.find('a').html()+'</span>');
    });



    $("#topnav li").hover(function() {
        $(this).find("span").stop().animate({
            marginTop: "-45"
        }, 250);
    }, function() {
        $(this).find("span").stop().animate({
            marginTop: "0"
        }, 250);
    });

});

Click Here

But I Agree as well with Andrew Peacock, I would use the same animation in sprites, leaving the same text and changing just background position. So you will skip 1 more loop to clone the text

0

精彩评论

暂无评论...
验证码 换一张
取 消