为什么我的img的位置没有改变超过10px?

时间:2016-03-30 14:44:17

标签: javascript html css

我想要一个img跟随鼠标,但它似乎没有这样做。 它移动10px后停止。 我不知道为什么它不起作用。当我将img的位置设置到鼠标的位置时,它可以工作。

var elem = document.getElementById("img").style;
var IE = document.all ? true : false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
var tempX;
var tempY;

function getMouseXY(e) {
  if (IE) {
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  } else {
    tempX = e.pageX;
    tempY = e.pageY;
  }
  
  if (tempX < 0) {
    tempX = 0;
  }
  
  if (tempY < 0) {
    tempY = 0;
  }
  
  document.Show.MouseX.value = tempX;
  document.Show.MouseY.value = tempY;
  return true;
}

document.onmousemove = getMouseXY;
document.onmouseover = update;

elem.left = "0px";
elem.bottom = "0px";
elem.position = "relative";

function update() {
  if (parseInt(elem.left) < (tempX - 10)) {
    elem.left = (parseInt(elem.left) + 1, 10).toString() + "px";
    console.log((parseInt(elem.left) + 1, 10).toString() + "px");
  }
  
  if (parseInt(elem.left) > (tempX - 10)) {
    elem.left = (parseInt(elem.left) - 1, 10).toString() + "px";
    console.log((parseInt(elem.left) - 1, 10).toString() + "px");
  }
  
  if (parseInt(elem.bottom) < (-tempY + 50)) {
    elem.bottom = (parseInt(elem.bottom) + 1, 10).toString() + "px";
    console.log((parseInt(elem.left) + 1, 10).toString() + "px");
  }
  
  if (parseInt(elem.bottom) > (-tempY + 50)) {
    elem.bottom = (parseInt(elem.bottom) - 1, 10).toString() + "px";
    console.log((parseInt(elem.left) + 1, 10).toString() + "px");
  }
}
<img id="img" src="//placehold.it/20.png">

0 个答案:

没有答案