Add javascript pixel values?

前端 未结 5 485
甜味超标
甜味超标 2021-02-05 14:45

Is there a way in javascript/jQuery to take two variables with values \"60px\" and \"40px\" and add them together to get \"100px\"?

Or in a more general sense, I\'m tryi

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 15:06

    You can do this by parsing the css.left value of the object, somewhat like this:

    $('#object2').css('left', (parseInt($('#object1').css('left')) + 60) + 'px');
    

    But you should keep in mind, that the css.left value might not be px but also %, em, etc. so the clean way would be using jQuery offset method as that would give you the correct pixels value.

    $('#object2').css('left', ($('#object1').offset().left + 60) + 'px');
    

提交回复
热议问题