分享栏
1.初始
HTML
<div class="move_box" id="move_box">
<img src="img/move_pic.jpg" >
<span>分享</span>
</div>
CSS
<style>
body,div,span,p{
padding: 0;
margin: 0;
}
.move_box {
width:300px;
position: relative;
left: -300px;/**/
top: 0;
}
.move_box img{
width: 300px;
}
.move_box span{
width: 50px;
height: 100px;
background: yellow;
position: absolute;
left: 300px;
top: 75px;
line-height: 100px;
color: cornflowerblue;
font-family:"Microsoft YaHei";
font-size: 1.5em;
font-weight: 200;
color: cornflowerblue;
}
</style>
JS:冗长且重复,相同的地方用函数,不同的地方传参数
window.onload=function () {
var oDiv=document.getElementById('move_box');
oDiv.onmouseover=function () {
startMove1();
}
oDiv.onmouseout=function () {
startMove2();
}
}
var timer;
function startMove1() {
clearInterval(timer);//先清理掉所有定时器
var oDiv=document.getElementById('move_box');
timer=setInterval(function () {
if (oDiv.offsetLeft==0){
clearInterval(timer);
}else {
oDiv.style.left=oDiv.offsetLeft+30+'px';//当前值每次+30px
}
},30)
}
function startMove2() {
clearInterval(timer);//先清理掉所有定时器
var oDiv=document.getElementById('move_box');
timer=setInterval(function () {
if (oDiv.offsetLeft==-300){
clearInterval(timer);
}else {
oDiv.style.left=oDiv.offsetLeft-30+'px';//当前值每次-30px
}
},30)
}
2.优化
传参数:速度值,标准值
/**
* Created by Administrator on 2017/9/13.
*/
window.onload=function () {
var oDiv=document.getElementById('move_box');
oDiv.onmouseover=function () {
startMove(30,0);
}
oDiv.onmouseout=function () {
startMove(-30,-300);
}
}
var timer;
function startMove(speed,iTarget) { //放入两个参数
clearInterval(timer);
var oDiv=document.getElementById('move_box');
timer=setInterval(function () {
if (oDiv.offsetLeft==iTarget){
clearInterval(timer);
}else {
oDiv.style.left=oDiv.offsetLeft+speed+'px';//当前值每次+"speed"px
}
},30)
}