function right() { square.style.left += 50+'px'; }
How to set not a fixed value in style.left, but add \ remove it?
function right() { square.style.left += 50+'px'; }
How to set not a fixed value in style.left, but add \ remove it?
This property is a string, so before increasing it, you need to convert it to a number, for example using the parseInt
function
function right() { square.style.left = (parseInt(square.style.left,10)+50)+'px'; }
Example:
var square = document.getElementById('square'); square.onclick = function() { right() } function right() { square.style.left = (parseInt(square.style.left, 10) + 50) + 'px'; }
#square { position: absolute; background-color: lime; width: 40px; height: 40px; }
<div id="square" style="left:0"></div>
You should pay attention to the fact that the left
property is set in inline styles, otherwise it will be equal to an empty line, and parseInt(square.style.left, 10)
will return NaN .
Another option is to use the function getComputedStyle , which allows you to get the current value of the property, as the default, in the case where the inline property is empty.
var square = document.getElementById('square'); square.onclick = function() { right() } function right() { square.style.left = (parseInt(square.style.left || getComputedStyle(square)['left'], 10) + 50) + 'px'; }
#square { position: absolute; background-color: lime; width: 40px; height: 40px; }
<div id="square" style="left:0"></div>
square
element does not move to the left by 50px when the right()
function is called. I can not understand why - Sergey Alekseevposition
not absolute , or relative , or some other square
is possibly selected, or the given link is null and a bunch of errors are written to the console - Grundyposition: absolute
Here's the full picture: square.onclick = function() {right()} function right() { square.style.left = (parseInt(square.style.left,10)+50)+'px'; }
square.onclick = function() {right()} function right() { square.style.left = (parseInt(square.style.left,10)+50)+'px'; }
- Sergey Alekseevbody
. #square { position: absolute; width: 100px; height: 100px; background-color: aquamarine; cursor: pointer; }
#square { position: absolute; width: 100px; height: 100px; background-color: aquamarine; cursor: pointer; }
When the right()
function was square.style.left = 50+'px';
, then when you click on an element, it once moved to the right - Sergey AlekseevSource: https://ru.stackoverflow.com/questions/553077/
All Articles