2015-10-24 102 views
2

这里是我的代码是不工作Javascript - 如何设置属性工作?

function gauche() { 
    var voiture = document.getElementsByClassName("voiture")[0]; 
    var position = window.getComputedStyle(voiture).left; 
    alert(position); 
    position = parseInt(position, 10) - 30 + "px"; 
    alert(position); 
} 

我想“VOITURE”位置30PX向左移动。所以我想从这个位置减去30。 这个警告很好30px,然后这个警报很好0px(因为30 - 30 = 0) 但不幸的是,它不会在我的网页上更新。我的“voiture”div始终为30像素,而不是宽度为0像素。谢谢

+0

你只是想念:'voiture.style.left = position'在最后。 – MinusFour

+0

以'var position'开头的语句只会将字符串从'left'属性复制到'position'。它只在_copy_上更新。但是,我们需要查看所有相关的HTML和CSS来解决这个问题,因为您不能简单地“写入”getComputedStyle属性。 – Xufox

回答

2

使用voiture.offsetLeft;而不是window.getComputedStyle(voiture).left;所以你不必解析它。

的HTMLElement.offsetLeft只读方法返回当前元素的左上角偏移到 所述的HTMLElement.offsetParent节点内左的 像素的数量。

,并设置简单的位置:voiture.style.left = voiture.offsetLeft - 30 + 'px';

offsetLeft doc

element.style.left doc

0

您需要使用DOM元素的style属性:

voiture.style.left = parseInt(position, 10) - 30 + "px"; 

此外,还有一个非常非常你的代码中错误的假设:你认为设置当前left到局部变量将其值限制到元素,而这不会发生。无论何时想要更改DOM元素(并且这适用于其任何属性),都需要再次设置其属性,而不是假定更改局部变量会更改元素。