从屏幕外显示div

时间:2016-12-09 14:37:57

标签: javascript

我正在执行此任务,我必须使用纯javascript在屏幕一侧显示div而不显示浏览器。这就是我到目前为止所做的:

function moveImg() {

  var div = document.getElementsByTagName('div')[0];

  var pos = 500;

  var id = setInterval(Move, 500);

  function Move() {
    if (pos <= 0) {
      clearInterval(id);

    } else {
      pos++;
      div.style.right = pos + 'px';
      div.style.top = pos + 'px';
    }
  }
}

moveImg()
div {
  width: 50px;
  height: 50px;
  background: tomato;
}
<div></div>

2 个答案:

答案 0 :(得分:1)

我一般都会使用变换。

我也做了一些数学,我已经对代码发表了评论,但随时可以询问是否有任何需要帮助理解的内容。

&#13;
&#13;
function moveImg() {
  var div = document.getElementsByTagName('div')[0];

  var posX = document.body.clientWidth - div.offsetWidth; // start position for X
  var posY = document.body.clientHeight - div.offsetHeight; // start position for Y
  var tarX = posX / 2; // end position for X
  var tarY = posY / 2; // end position for Y
  var time = 5; // how many seconds should the animation take
  var fps = 60; // frames per second, heigher is smoother but requires more power
  var stepX = ((posX - tarX) / (time * fps)); // how far X should move each frame
  var stepY = ((posY - tarY) / (time * fps)); // how far Y should move each frame

  var id = setInterval(Move, (1000 / fps));

  div.style.transform = "translate(" + posX + "px, " + posY + "px)";
  div.style.opacity = "1";

  function Move() {
    if (posX <= tarX && posY <= tarY) {
      clearInterval(id);
    } else {
      posX -= stepX;
      posY -= stepY;
      div.style.transform = "translate(" + posX + "px, " + posY + "px)";
    }
  }
}
moveImg();
&#13;
body {
  margin: 0;
  width: 100vw;
  height: 100vh;
}
div {
  display: inline-block;
  color: white;
  padding: 15px 30px;
  background: tomato;
  opacity: 0;
}
&#13;
<div>Example!</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

就像评论中所说的那样,你不会说出你希望div移动的方向,也不知道应该从哪个方向开始。

我设置了顶部的起始位置:100,左:100,每秒topleft值减少1px

&#13;
&#13;
  function moveImg() {
  var div = document.getElementsByTagName('div')[0];
  var pos = 100;
  var id = setInterval(Move, 500);

 function Move() {
   if (pos <= 0) {
     clearInterval(id);
   } else {
     pos--;
     div.style.left = pos + 'px';
     div.style.top = pos + 'px';
   }
  }
}

moveImg()
&#13;
div {
  width: 50px;
  height: 50px;
  background: tomato;
  position: relative;
  top: 100px;
  left: 100px;
}
&#13;
<div></div>
&#13;
&#13;
&#13;