在jQuery.css()中有条件地设置属性

Ale*_*lex 3 html css jquery

foo在页面上有40个,每个都在另一个函数中分配了一个左/上值.

$('.foo').css({
  top: isOn ? current_top_value_here : 500,
  left: isOn ? current_left_value_here : 500
});
Run Code Online (Sandbox Code Playgroud)

所以,如果isOn是真的,我想保持顶部和左侧属性不被修改.我怎样才能做到这一点?

kap*_*apa 5

这样您就可以确保只在需要时才添加它们.首先使用您想要分配的值设置对象,并有条件地添加更多.然后你可以将对象传递给你.css().

var cssProperties={
    'color' : 'yellow',
    ...
};

if (isOn) {
    cssProperties.top=500;
    cssProperties.left=500;
    /* alternative: $.extend(cssProperties, { 'top': 500, 'left': 500 }); */
}

$('.foo').css(cssProperties);
Run Code Online (Sandbox Code Playgroud)