1.box.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>广告</title>
<link rel="stylesheet" type="text/css" href="box.css"/>
<script src="box.js"></script>
</head>
<body>
<div id="box">
<span id="smallbox"></span>
</div>
</body>
</html>
2.box.css代码:
body {
padding: 0px;
margin: 0px;
}
#box {
height: 200px;
width: 200px;
background-color: rebeccapurple;
-webkit-border-radius: 5%;
-moz-border-radius: 5%;
border-radius: 5%;
position: relative;
left: -200px;
}
#smallbox {
height: 50px;
width: 20px;
position: absolute;
left: 200px;
top: 75px;
background-color: red;
-webkit-border-radius: 5%;
-moz-border-radius: 5%;
border-radius: 5%;
}
3.box.js代码:
window.onload = function () {
var box = document.getElementById('box');
box.onmouseover = function () {
move(0);
}
box.onmouseout = function () {
move(-200);
}
}
var timer = null;
function move(target) {
clearInterval(timer);
var box = document.getElementById('box');
timer = setInterval(function () {
var speed = (target - box.offsetLeft) / 20;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (box.offsetLeft == target) {
clearInterval(timer);
} else {
box.style.left = box.offsetLeft + speed + 'px';
}
}, 30);
}