<分区>
<分区>
如果单击左右按钮,我如何实现将 div (sellBody) 向左或向右移动 50px?
使用以下代码,框仅向左或向右移动 50px 一次。我知道为什么,但我不知道如何让它每次单击任一按钮时都向任一侧移动 50px。
function slideLeft(sellBody) {
var slideLeft = document.getElementById("sellBody");
slideLeft.style.transition = "left 1.0s linear 0s";
slideLeft.style.left = "-50px";
}
function slideRight(sellBody) {
var slideRight = document.getElementById("sellBody");
slideRight.style.transition = "right 1.0s linear 0s";
slideRight.style.right = "-50px";
}
最佳答案
"with the following code the box is only moved 50px to the left or right once. I know why but i don't know how to make it move 50px to either side EVERY time i click on either button."
您需要获取当前值并从中减去 50:
var currentLeft = parseFloat(slideLeft.style.left);
slideLeft.style.left = (currentLeft - 50) + "px";
当前样式的格式为 "50px"
,所以使用 parseFloat()
function获取数字并忽略单位以便您可以进行减法,然后将 "px"
连接到结果。
关于javascript - 如何使用 javascript 添加 css 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776646/