下面的jQuery怎么写得更好一点?(褪色)



我是jQuery的新手,我想知道如何更好地编写以下代码?

$( "p:first" ).css({opacity:0.5})
$( "p:first" ).mouseover(function() {
  $( this ).fadeTo( "fast", 1 );
});
$( "p:first" ).mouseout(function() {
  $( this ).fadeTo( "fast", 0.5 );
});

您可以使用 jQuery 链接,并且 hover 方法将 mouseenter/mouseleave 函数包装在一个简洁的方法中:

$("p:first").css({opacity:0.5})
    .hover(function() {
        $( this ).fadeTo( "fast", 1 );
    }, function() {
        $( this ).fadeTo( "fast", 0.5 );
    });

如果需要 mouseovermouseout而不是 enter/leave您可以使用 .on 重载:

$("p:first").css({opacity:0.5})
    .on({
        mouseover: function() {
            $( this ).fadeTo( "fast", 1 );
        },
        mouseout: function() {
            $( this ).fadeTo( "fast", 0.5 );
        }
    });
$( "p:first" ).css({opacity:0.5}).on({
    mouseover:function() {
        $( this ).fadeTo( "fast", 1 );
    },
    mouseout:(function() {
        $( this ).fadeTo( "fast", 0.5 );
    }
});

你应该使用链接

$("p:first").css({
    'opacity': 0.5
}).on({
  mouseover: function () {
    $(this).fadeTo("fast", 1);
  },
  mouseout: (function () {
    $(this).fadeTo("fast", 0.5);
  }
 });

怎么样:

$( "p:first" ).css({opacity:0.5})
    .hover(function() {
        $( this ).fadeTo( "fast", 1 );
    },
    function() {
        $( this ).fadeTo( "fast", 0.5 );
    });

您可以将chaining.hover() 一起使用来完成您的任务。

尝试

$( "p:first" ).css({'opacity':0.5}).selector.hover(function() {
                                       $( this ).fadeTo( "fast", 1 );
                                   },function() {
                                       $( this ).fadeTo( "fast", 0.5 );
                                    });

最新更新