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?

Share Improve this question edited Sep 29, 2010 at 17:40 user113716 323k64 gold badges453 silver badges441 bronze badges asked Sep 29, 2010 at 17:19 bbabba 15.2k11 gold badges31 silver badges26 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5
var 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