繁体   English   中英

如何将重复的CSS值存储在变量中,以减少代码的重复性?

[英]How can I store the repeating css values in varialbles to make the code less repetitive?

  $('ul#range-drop li#product1')
    .css( {backgroundPosition: '-914px 0px'} )
    .mouseover(function(){
      if (!($('ul#range-drop li#product1 a').hasClass("current")) ) {
        $(this).css( {background: "none"} );
        $(this).parent().stop().animate({backgroundPosition: '-914px -12px' }, {duration:400, easing: 'easeInOutQuint'});
      }
   })

  .mouseout(function(){
   $(this).parent().stop().animate({backgroundPosition : '-914px 0px'}, {duration:400, easing: 'easeInOutQuint'});
   });

对于每个导航元素重复此代码块,并为背景位置设置不同的值

将此代码放入一个函数中,其中输入参数是您要将代码绑定到的元素ID的名称,背景位置以及任何其他更改信息。 然后,每个元素只有一行(方法调用),但是代码的核心仅编写了一次。

例如(将它们放在一起,没有对其进行测试)

applyCSS('ul#range-drop li#product1', -194, 0)

function applyCSS(id, posx, posy)
{
  $(id)
    .css( {backgroundPosition: posx + 'px ' + posy + 'px'} )
    .mouseover(function(){
      if (!($(id).hasClass("current")) ) {
        $(this).css( {background: "none"} );
        $(this).parent().stop().animate({backgroundPosition: posx + 'px ' + posy + 'px'},     {duration:400, easing: 'easeInOutQuint'});
      }
   })

  .mouseout(function(){
   $(this).parent().stop().animate({backgroundPosition: posx + 'px ' + posy + 'px'},     {duration:400, easing: 'easeInOutQuint'});
   });

}

您应该将值存储在data- attribute或JavaScript映射中。

var map = {
  product1 : ['-914px 0px', '-914px -12px']
}

$('ul#range-drop li').each(function() {
    $(this).css('backgroundPosition', map[this.id][0]);
}).mouseover(function() {
    if (!($(this).hasClass("current"))) {
        $(this).css({
            background: "none"
        });
        $(this).parent().stop().animate({
            backgroundPosition: map[this.id][1]
        }, {
            duration: 400,
            easing: 'easeInOutQuint'
        });
    }
}).mouseout(function() {
    $(this).parent().stop().animate({
        backgroundPosition: map[this.id][0]
    }, {
        duration: 400,
        easing: 'easeInOutQuint'
    });
});​

地图将默认背景位置作为数组中的第一个元素,将动画位置作为第二个元素(当然,您可以根据需要更改此位置,这只是一个开始的想法)。

    $('ul#range-drop li#product1')
        .css( {backgroundPosition: '-914px 0px'} )
        .mouseover(function(){
          if (!($('ul#range-drop li#product1 a').hasClass("current")) ) {
            $(this).css( {background: "none"} );
           animation($(this),"-12");
          }
       })
          .mouseout(function(){
      animation($(this),"0")
       });

function animation(obj,valu)
{       obj.parent().stop().animate({backgroundPosition : '-914px '+valu+'px'}, {duration:400, easing: 'easeInOutQuint'});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM