Javascript 如何使用 jquery 设置边距?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5314532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set margin with jquery?
提问by gigi
I am doing this:
我正在这样做:
var sId=id.toString();
var index=sId.substring(3);
var mrg=index*221;
var el=$(id);
el.css('margin-left',mrg+'px'); and el.css('marginLeft',mrg+'px');
el is the element i want to set the margin to (correctly retrieved) and mrg is the value of the new margin
el 是我想将边距设置为(正确检索)的元素,而 mrg 是新边距的值
If i do $('#test1').css('margin-left',200);
or $('#test1').css('marginLeft',200);
it works in both ways, it's something wrong with the way i set the property.
如果我执行 $('#test1').css('margin-left',200);
或者$('#test1').css('marginLeft',200);
它以两种方式工作,那么我设置属性的方式有问题。
The correct way is var el=$('#'+id);
正确的方法是var el=$('#'+id);
回答by choise
try
尝试
el.css('margin-left',mrg+'px');
回答by JohnP
Set it with a px value. Changing the code like below should work
使用 px 值设置它。像下面这样更改代码应该可以工作
el.css('marginLeft', mrg + 'px');