简体   繁体   中英

Addition of a positive number and a negative number

I made a function to move an element base on there left CSS value. My function work in one direction but I realize a strange problem in the other direction.

First I extract the left value of a element :

$left_position = element.css('left').replace(/[^-\d\.]/g, ''); // left_position = -400

now when I add a positive value to that, for the new position :

$new_left_position = $left_position + 400; 

The result I was expected was 0 but instead the result is : -400400

If I replace the "+" sign by a "-" sign it work the result is -800

Any idea why? Thanks

Parse it to integer, you are concatinating it because one element ($left_position) is a string.

$new_left_position = parseInt($left_position) + 400; 

function ".replace()" will ofcourse always return a string so your variable is a string aswell.

In javascript the + sign is for string concatantion on strings.

var string = "400";
console.log(string + 400); //400400
console.log(parseInt(string) + 400); //800

Using ParseInt('$variableName') you can achieve your desired result.

I hope following will also helpful in your work. Using simple jQuery code you can move things easily as follows:

HTML:

<input type="button" value="To Left" onclick="moveStuff('-=100px')" />
<input type="button" value="To Right" onclick="moveStuff('+=100px')" />
<div id="stuff" style="padding:10px;background-color:#ff00f0;width:120px">I AM MOVING</div>

jQuery Function:

function moveStuff(px) {
$('#stuff').animate({
    'marginLeft' : px
 },1000);
}

WORKING SOLUTION on JS Bin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM