一、简单实现分享到
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#div1 {
width: 100px;
height: 200px;
background: #ccc;
position: absolute;
left: -100px;
top: 30%;
}
#div1 span {
width: 20px;
height: 60px;
line-height: 20px;
text-align: center;
left: 100px;
top: 70px;
background: yellow;
position: absolute;
/*display: block;*/
}
</style>
<script>
var timer = null;
// var iSpeed = null;
window.onload = function() {
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function() {
startMove(0);
}
oDiv.onmouseout = function() {
startMove(-100);
}
}
function startMove(iTarget) {
var oDiv = document.getElementById('div1');
var iSpeed = 10;
if (oDiv.offsetLeft > iTarget) { //设置速度正负
iSpeed = -iSpeed;
}
clearInterval(timer);
timer = setInterval(function() {
if (oDiv.offsetLeft == iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
}
}, 30)
}
</script>
</head>
<body>
<div id="div1">
<span>分享到</span>
</div>
</body>
</html>
二、匀速运动框架
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#div1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 500px;
}
#div2 {
width: 1px;
height: 300px;
background: black;
position: absolute;
left: 300px;
}
</style>
<script>
window.onload = function() {
}
var timer = null;
function starMove(iTarget) {
var oDiv = document.getElementById('div1');
clearInterval(timer); //防止定时器累加
timer = setInterval(function() {
var iSpeed = 0;
if (oDiv.offsetLeft < iTarget) {
iSpeed = 7;
} else {
iSpeed = -7;
}
if (Math.abs(oDiv.offsetLeft - iTarget) < 7) { //判断是否到达终点一次运动的距离都不够的时候停止
clearInterval(timer); //清除定时器
oDiv.style.left = iTarget + 'px';
} else {
oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
}
}, 30);
}
</script>
</head>
<body>
<input type="button" name="" value="运动" οnclick="starMove(300)">
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>