开发者

jQuery passing variabile to .css({})

I have the following function:

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

this works.

I 开发者_运维知识库am looking for a way to add left: leftVal+"px", top:topVal+"px" as a variable and make my function:

$("#myId").css({myCSSstuff});

I've tryed

var myCSSstuff= "left: "+leftVal+"px, top:"+topVal+"px"

but it does not work. Is there a way to do this? Thanx.


You can do it like this:

var myCSSstuff = { left: leftVal, top: topVal };
$("#myId").css(myCSSstuff);

The {} notation is for objects or associative arrays.

There are two ways you can add more properties:

myCSSstuff.color = 'red';
myCSSstuff['color'] = 'red';

The second approach allows you to use strings for the property name, i.e.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜