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

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

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

所以,我想离开顶部&如果isOn为true,则保留未修改的左侧属性.我怎样才能做到这一点?

解决方法

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

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

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

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...