侧边隐藏分享栏
一、Html布局
<body>
<aside id="menu">
<ul>
<li>QQ</li>
<li>wechat</li>
<li>weibo</li>
</ul>
<span id="share">分享</span>
</aside>
</body>
二、Css样式
<style>
body{
margin:0;
padding: 0;
}
ul{
margin:0;
}
ul li{
padding-top:20px;
}
#menu{
width: 200px;
height:200px;
background:red;
position:relative;
left:-200px;
top:0;
}
#menu span{
width:20px;
height: 50px;
background-color: blue;
position: absolute;
left:200px;
top: 75px;
}
</style>
三、Js部分
<script>
window.onload = function(){
var oDiv = document.getElementById("menu");
oDiv.onmouseover = function(){
startMove(0);
}
oDiv.onmouseout = function(){
startMove(-200);
}
}
var timer = null;
//定义定时器
startMove = function(iTarget){
//目标值ITarget(与隐藏的区域宽度相同)
clearInterval(timer);
//开启定时器前先关闭所有定时器
var oDiv = document.getElementById("menu");
timer = setInterval(function(){
var speed = 0;
//移入移出速度
if(oDiv.offsetLeft > iTarget){
//这里为了方便直接使用offsetWidth属性,但给div加入border margin等会有bug
//应该用 currentStyle 或 getComputedStytle获取样式
speed = -10;
}else{
speed = 10;
}
if(oDiv.offsetLeft == iTarget){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + speed + "px";
}
},30)
}
</script>
<script>
window.onload = function(){
var oDiv = document.getElementById("menu");
oDiv.onmouseover = function(){
startMove(0);
}
oDiv.onmouseout = function(){
startMove(-200);
}
}
var timer = null;
//定义定时器
startMove = function(iTarget){
//目标值ITarget(与隐藏的区域宽度相同)
clearInterval(timer);
//开启定时器前先关闭所有定时器
var oDiv = document.getElementById("menu");
timer = setInterval(function(){
var speed = (iTarget - oDiv.offsetLeft )/20;
//越靠近目标值速度越小
speed = speed > 0?Math.ceil(speed):Math.floor(speed);//缓冲运动所必须
//向右移动速度为正数,向左为负数
//将speed取整是为了避免后面设置oDiv.style.left 有小数部分,显示不完全
if(oDiv.offsetLeft == iTarget){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + speed + "px";
}
},30)
}
</script>
网友评论