Add javascript pixel values?

前端 未结 5 481
甜味超标
甜味超标 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're looking for the parseInt() function.

    var left1 = "40px";
    var left2 = "60px";
    
    // Add the integer values of the left values together
    var leftTotal = parseInt( left1, 10 ) + parseInt( left2, 10 ) + "px";
    

    Also worth investigating is the parseFloat() method. It does the same thing as parseInt(), but works on numbers with decimals (aka floating point values).

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2021-02-05 15:21

    Probably the most efficient way is

    parseInt("40px", 10) + parseInt("60px", 10) + "px"
    

    The 10's in the parseInt calls are necessary to protect against the value being mistakenly calculated in something other than base 10.

    0 讨论(0)
  • 2021-02-05 15:22
    var shiftedRight = (parseFloat($('#object1').css('left')) + 60) + 'px';
    $('#object2').css('left', shiftedRight);
    

    parseFloat will parse only the prefix of the string that is a number.

    0 讨论(0)
  • 2021-02-05 15:30

    remove px from strings, add values, then add px back

      (parseInt("40px".replace(/px/,""))+60)+"px"
    
    0 讨论(0)
提交回复
热议问题