<!DOCTYPE = html>
<html>
<head>
<title></title>
<style>
body{
margin: 0px;
padding: 0px;
}
.red{
background-color:red;
width:200px;
height:200px;
position:relative;
left:-200px;
top:0px;
}
.blue{
background:blue;
width:20px;
height:50px;
position:absolute;
left:200px;
top:75px;
}
</style>
<script src="file:///F:front end/jquery/jquery-1.11.3.min.js"></script>
</head>
<body>
<div class="red" id="cf1"><div class="blue" id="cf">分享</div></div>
<script>
window.onload = function(){
var onDiv = document.getElementById("cf1");
onDiv.onmouseover = function(){
startmove(0);
}
onDiv.onmouseout = function(){
startmove(-200);
}
}
var timer ;
function startmove(target){
clearInterval(timer);//清除定时器,以免多次触发定时器导致速度越来越快而不是匀速前进
var onDiv1 = document.getElementById("cf1");
timer = setInterval(function(){
var speed = 0;
if(onDiv1.offsetLeft<target){
speed = 10;
}else{
speed = -10;
}
if(onDiv1.offsetLeft==target){
clearInterval(timer);
}
else{
onDiv1.style.left = onDiv1.offsetLeft+speed+'px';
}
},30)
}
</script>
</body>
</html>
小结:
一、css部分:
1、别忘记样式初始化;
2、复习css文件的引用方式;(类引用方式)
3、复习绝对定位和相对定位关系(父关系用relative;子关系用absolute)
二、js部分:
1、element.style.left&element.offsetLeft区别:
(1)前者单位是px,是字符串;后者单位是数值;
(2)其他参见:http://www.jb51.net/article/43981.htm
2、思路开始不够清晰,未能抽象出鼠标放上和移开关键变量——目标位置不同而已
3、函数参数尽可能少(在能达成目标的情况下)
4、鼠标作用对象设置为父级div最好,不然会出现闪烁情况(刚调用onmouseover,目标移除,又调用了onmouseout)
5、注意清除定时器(1、防止移动时速度不稳定 2、到目标位置停止运动)
三、其他:
Q:谷歌浏览器解除禁止弹出窗口?
A:设置——高级设置——隐私设置——内容设置——弹出式窗口,进行相关设置。