分享侧边栏——js代码

来源:互联网 发布:php curl 301跳转 编辑:程序博客网 时间:2024/06/03 19:04
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{margin: 0;padding: 0;}
#div1{position: relative;width: 150px;height: 150px;background: red; top: 50px; left: -150px; }
#sp{position: absolute; background: #ccc;top: 40px;right: -20px; width: 20px;height: 70px;}
</style>
<script>
// //第一种方法:
// window.onload=function(){
// var oDiv1=document.getElementById('div1'); 
// oDiv1.onmouseover=function()
// {
// startMove();
// };
// oDiv1.onmouseout=function(){
// startMove2();
// };
// }
// //设一个全局变量 timer=null; 
// var timer=null;
// function startMove(){
// clearInterval(timer);
// var oDiv1=document.getElementById('div1');
// timer=setInterval(function(){
// if (oDiv1.offsetLeft==0){
// clearInterval(timer);
// }
//                 //若用style.left要加px;即使是0也要加px;否则不能识别  不会跑startMove函数。
// if (oDiv1.style.left==0+'px'){
// clearInterval(timer);
// }
// else{
// oDiv1.style.left=oDiv1.offsetLeft+10+'px';
// }
// },30) 
// }
// function startMove2(){
// clearInterval(timer);
// var oDiv1=document.getElementById('div1');
// timer=setInterval(function(){
// if (oDiv1.offsetLeft==-150){
// clearInterval(timer);
// }
// else{
// oDiv1.style.left=oDiv1.offsetLeft-10+'px';
// }
// },30) 
//
//第二种方法:
// window.onload=function(){
// var oDiv=document.getElementById('div1'); 
// oDiv.onmouseover=function()
// {
// startMove(oDiv,0,10);
// };
// oDiv.onmouseout=function(){
// startMove(oDiv,-150,-10);
// };
// }
// //设一个全局变量 timer=null; 
// var timer=null;
// function startMove(obj,iTarget,speed){
// clearInterval(timer);
// timer=setInterval(function(){
// if (obj.style.left==iTarget+'px'){
// clearInterval(timer);
// }
// else{
// obj.style.left=obj.offsetLeft+speed+'px';
// }
// },30) 
//


//第三种方法  只需要一个参数,使得函数调用越来越简单,但是这是在知道speed的情况下
window.onload=function(){
var oDiv=document.getElementById('div1'); 
oDiv.onmouseover=function()
{
startMove(0); 
};
oDiv.onmouseout=function(){
startMove(-150); 
};
}
//设一个全局变量 timer=null; 
var timer=null;
function startMove(iTarget){ 
var oDiv=document.getElementById('div1');  
clearInterval(timer);
timer=setInterval(function(){
var speed=0;
               if(iTarget<oDiv.offsetLeft)
{
speed=-10;
}
else
{
speed=10;
}
if (oDiv.offsetLeft==iTarget)
{
clearInterval(timer);
}
else
{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
document.title=speed;
}
},30) 
}  
</script>
</head>
<body>
<div id="div1">
<span id="sp">分享到</span>
</div>
</body>
</html>
原创粉丝点击