javascript - jQuery adding to css element - Stack Overflow

I have the id of my element. I need to add a given value (determined by a variable in the javascript) t

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; });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745578976a4634139.html

相关推荐

  • javascript - jQuery adding to css element - Stack Overflow

    I have the id of my element. I need to add a given value (determined by a variable in the javascript) t

    6小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信