我是jQuery的新手,我想知道如何更好地编写以下代码?
$( "p:first" ).css({opacity:0.5})
$( "p:first" ).mouseover(function() {
$( this ).fadeTo( "fast", 1 );
});
$( "p:first" ).mouseout(function() {
$( this ).fadeTo( "fast", 0.5 );
});
答案 0 :(得分:2)
你应该使用链接
$("p:first").css({
'opacity': 0.5
}).on({
mouseover: function () {
$(this).fadeTo("fast", 1);
},
mouseout: (function () {
$(this).fadeTo("fast", 0.5);
}
});
答案 1 :(得分:2)
你可以使用jQuery chaining,hover方法也可以用一个简洁的方法包装mouseenter
/ mouseleave
函数:
$("p:first").css({opacity:0.5})
.hover(function() {
$( this ).fadeTo( "fast", 1 );
}, function() {
$( this ).fadeTo( "fast", 0.5 );
});
如果您需要mouseover
,mouseout
而不是enter
/ leave
,则可以使用.on
重载:
$("p:first").css({opacity:0.5})
.on({
mouseover: function() {
$( this ).fadeTo( "fast", 1 );
},
mouseout: function() {
$( this ).fadeTo( "fast", 0.5 );
}
});
答案 2 :(得分:2)
$( "p:first" ).css({opacity:0.5}).on({
mouseover:function() {
$( this ).fadeTo( "fast", 1 );
},
mouseout:(function() {
$( this ).fadeTo( "fast", 0.5 );
}
});
答案 3 :(得分:1)
怎么样:
$( "p:first" ).css({opacity:0.5})
.hover(function() {
$( this ).fadeTo( "fast", 1 );
},
function() {
$( this ).fadeTo( "fast", 0.5 );
});
答案 4 :(得分:0)
您可以使用chaining
和 .hover() 来完成任务。
尝试,
$( "p:first" ).css({'opacity':0.5}).selector.hover(function() {
$( this ).fadeTo( "fast", 1 );
},function() {
$( this ).fadeTo( "fast", 0.5 );
});