div moved in a straight line
step:
1) First, add a div in the body, and proceed to set div style. In order to move div, set position absolute as , left to 0 , right is set to 0 .
2) Then we look to clear the default style. (* {} Is this part).
3) script function in the move to make my move div certain pixels each call.
code show as below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
4) run first look to see whether there is my div, the effect is shown below.
![](https://img2018.cnblogs.com/blog/1817586/201910/1817586-20191001234036056-87553530.png)
5) achieve move, make the following changes in the script, you can look back to the browser, div at this time is the horizontal movement of friends.
<body>
<div></div>
<script type="text/javascript">
var speedX = 3;//在move之外,先有一个水平移动的速度
var div = document.querySelector('div');//方便move隔一小段时间调用
//实现move
function move(){
//在move中取得当前元素所在的left值,调用getComputedStyle传入div
//注意:left是个字符串,且后面可能跟着px单位,在使用之前先用parseInt解析
var currentLeft = parseInt(window.getComputedStyle(div).left) ;
var currentTop = parseInt(window.getComputedStyle(div).top) ;
var left = currentLeft + speedX;//计算left值
div.style.left = left + 'px';//设置水平移动
}
//调用move函数
setInterval(function(){
move()
},20);
</script>
</body>
6) Similarly, the parameters set in the vertical direction, the vertical direction can be realized.
var speedY = 4;//垂直方向
var top = currentTop + speedY;//计算top值
div.style.top = top + 'px'; //设置垂直移动
7) diagonal movement is the horizontal direction and the vertical direction are set parameter.