Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/33.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_Css_Variables - Fatal编程技术网

jQuery将变量传递给.css({})

jQuery将变量传递给.css({}),jquery,css,variables,Jquery,Css,Variables,我有以下功能: $("#myId").css({left: leftVal+"px", top:topVal+"px"}); 这很有效 我正在寻找将left:leftVal+“px”,top:topVal+“px”添加为变量的方法,并使我的函数: $("#myId").css({myCSSstuff}); 我试过了 var myCSSstuff= "left: "+leftVal+"px, top:"+topVal+"px" 但它不起作用。 有办法做到这一点吗? 塔克斯 您可以这样做: v

我有以下功能:

$("#myId").css({left: leftVal+"px", top:topVal+"px"});
这很有效

我正在寻找将
left:leftVal+“px”,top:topVal+“px”
添加为变量的方法,并使我的函数:

$("#myId").css({myCSSstuff});
我试过了

var myCSSstuff= "left: "+leftVal+"px, top:"+topVal+"px"
但它不起作用。 有办法做到这一点吗?
塔克斯

您可以这样做:

var myCSSstuff = { left: leftVal, top: topVal };
$("#myId").css(myCSSstuff);
{}
符号用于对象或关联数组

有两种方法可以添加更多属性:

myCSSstuff.color = 'red';
myCSSstuff['color'] = 'red';
第二种方法允许使用字符串作为属性名,即

var prop = 'color';
myCSSstuff[prop] = 'red';

您可以这样做:

var myCSSstuff = { left: leftVal, top: topVal };
$("#myId").css(myCSSstuff);
{}
符号用于对象或关联数组

有两种方法可以添加更多属性:

myCSSstuff.color = 'red';
myCSSstuff['color'] = 'red';
第二种方法允许使用字符串作为属性名,即

var prop = 'color';
myCSSstuff[prop] = 'red';

您可以省略
'px'
部分。(jquery会自动处理)thanx,这很有效!。如果我需要在数组中的某个点添加另一个变量,该怎么办。类似于myCSSstuff=myCSSstuff+{color:Something}。我该怎么做?再次使用Thanx,您可以省略
'px'
部分。(jquery会自动处理)thanx,这很有效!。如果我需要在数组中的某个点添加另一个变量,该怎么办。类似于myCSSstuff=myCSSstuff+{color:Something}。我该怎么做?又来了