Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在jQuery.css()中有条件地设置属性_Jquery_Html_Css - Fatal编程技术网

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

在jQuery.css()中有条件地设置属性,jquery,html,css,Jquery,Html,Css,我在页面上有40个foo,每个都在另一个函数中分配了一个左/顶值 $('.foo').css({ top: isOn ? current_top_value_here : 500, left: isOn ? current_left_value_here : 500 }); 因此,如果isOn为true,我希望保持顶部和左侧属性不变。我该怎么做呢?最好的办法可能就是根本不打电话。如果在同一语句中设置了其他css,只需将其拆分: if(!isOn){ $('.foo').css({

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

$('.foo').css({
  top: isOn ? current_top_value_here : 500,
  left: isOn ? current_left_value_here : 500
});

因此,如果
isOn
为true,我希望保持顶部和左侧属性不变。我该怎么做呢?

最好的办法可能就是根本不打电话。如果在同一语句中设置了其他css,只需将其拆分:

if(!isOn){
  $('.foo').css({
    top: 500,
    left: 500
  });
}

$('.foo').css({
   // other stuff
});

这样,您可以确保仅在需要时添加它们。首先使用要指定的值设置对象,然后有条件地添加更多值。然后,您可以将对象传递给
.css()


什么是
isOn
?Javascript变量?但这意味着我必须复制代码,添加20行+。我还有一个动画功能,需要有条件地对这些属性设置动画…至少先保存jQuery集合,运行两次
$('.foo')
不是一个好的做法。@baz-Yup,只是说明了这个想法,而不是优化它。尽管如此,您的想法还是更好,因为问题已经得到了进一步的解释。无意冒犯,只是想提一下,以防稍后有人访问此问题以使用代码示例:)。如果我误解了某些内容,请展示更多代码,并更详细地解释您需要的内容。也许有好的选择。
var cssProperties={
    'color' : 'yellow',
    ...
};

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

$('.foo').css(cssProperties);