admin管理员组文章数量:1431700
I have the id of my element. I need to add a given value (determined by a variable in the javascript) to one of the element's css attributes. I.e. given an element id=my_id
how do I add x
to that element's margin-top
attribute?
I have the id of my element. I need to add a given value (determined by a variable in the javascript) to one of the element's css attributes. I.e. given an element id=my_id
how do I add x
to that element's margin-top
attribute?
3 Answers
Reset to default 5var x = 20;
$('#my_id').css('margin-top', function(index, value) {
if (isNaN(parseInt(value)))
return x;
return parseInt(value) + x
});
var inc = 20;
var mt = parseInt($('#my_id').css('margin-top').replace('px',''));
$('#my_id').css('margin-top',(mt+inc)+"px");
This assumes, of course, you always use px for margin-top values. I've used this reliably for quite some time.
One approach is to use jQuery's .animate()
method, but give it a duration of 0
. This allows you to send the +=
operator as a string, and concatenate the value of x
.
var x = 50;
$('#my_id').animate({marginTop: '+=' + x}, 0);
Another way would be to pass a function as the second parameter to jQuery's .css()
method. The return value will be the current value plus x
. This requires jQuery 1.4 or later.
var x = 50;
$('#my_id').css('margin-top', function(i,val) { return (parseInt(val) || 0) + x; });
本文标签: javascriptjQuery adding to css elementStack Overflow
版权声明:本文标题:javascript - jQuery adding to css element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745578976a2664505.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论