变量未更改

Variable not being changed

本文关键字:变量      更新时间:2023-09-26

使用以下代码,每当文档悬停在屏幕上时,我都会尝试在屏幕上移动一个小点。

问题是,初始化但未定义的"x.style.left"属性在第一次更新时(我用console.log检查了它),但之后它不再更新,即使我在代码中进一步更改了它,它仍保持该值。

这是代码:

var x = document.getElementById("bot");
document.onmouseover = function(){move()};

function myfunc(){
}
function move(){
       x.style.position="relative";
       x.style.left;
       console.log(x.style.left);
       x.style.left=String(10 + 10) + "px";
       console.log(x.style.left);
}

小提琴:https://jsfiddle.net/puxg59td/

每次都需要获取值并添加到其中。

function move(){
       x.style.position="relative";
       var value = parseInt(x.style.left);
       if (!value) {
           value = 0;
       }
       console.log(x.style.left);
       x.style.left=String(value + 10 + 10) + "px";
       console.log(x.style.left);
}

Fiddle:https://jsfiddle.net/puxg59td/1/

已更新(以下是jsfiddle更新:https://jsfiddle.net/puxg59td/10/):

var x = document.getElementById("bot");
document.onmouseover = function(){move()};
function move(){
    x.style.position="relative";
    var curLeft = parseInt(x.style.left) || 0;
    x.style.left= (curLeft + 10) + "px";
}
#body{
    border:2px solid black;
    height:100px;
}
#bot{
    height:1px;
    width:1px;
    background-color:black;
    border:2px solid black;
}
<div id="body">
  <div id="bot"></div>
</div>

你必须增加职位。你的问题是,你总是给x相同的20px左样式;试试这个:

function move(x){
   x.style.position="relative";
   var l = x.getBoundingClientRect().left;
   console.log(l);
   x.style.left =l + 20 + "px";
   console.log(x.style.left);
}