模擬百度分享側邊欄的彈出與滑入效果。當鼠標移入#div1分享側邊欄,#div1分享側邊欄區塊勻速滑出直至其全部露出。當鼠標移除#div1分享側邊欄,#div1分享側邊欄區塊勻速滑入隱藏,直至恢復初始位置。若#div1區塊未全部露出時,鼠標移出,#div1區塊則開始滑入隱藏;若#div1區塊未全部滑入隱藏,鼠標移入,則div1區塊則開始勻速彈出。
示例圖片
<!DOCTYPE html>
<html>
<head>
<title>JS運動框架案例:類百度分享製作</title>
<meta charset="UTF-8">
</head>
<style>
#div1 {
width: 150px;
height: 200px;
background: green;
position: absolute;
left: -150px;
top: calc(50% - 100px);
}
#div1 span {
width: 20px;
height: 60px;
line-height: 20px;
right: -20px;
top: 70px;
background: blue;
position: absolute;
}
html,
body {
margin: 0;
padding: 0;
}
</style>
<script>
window.onload = function () {
// 補充代碼
}
</script>
<body>
<div id='div1'>
<span>分享到</span>
</div>
</body>
</html>
參考代碼:
window.onload = function () {
oDiv=document.getElementById('div1')
oDiv.onmouseover = function () {
var speed = 10;
var timer = null;
var iTarget = 150;
clearInterval(oDiv.timer);
oDiv.timer = setInterval(function () {
if (oDiv.offsetLeft >= 0) {
clearInterval(oDiv.timer);
} else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
}, 30);
}
oDiv.onmouseout = function () {
var speed = 10;
var timer = null;
var iTarget = 150;
clearInterval(oDiv.timer);
oDiv.timer = setInterval(function () {
if (oDiv.offsetLeft <= -150) {
clearInterval(oDiv.timer);
} else {
oDiv.style.left = oDiv.offsetLeft - speed + 'px';
}
}, 30);
}
}
ps:上述代碼屬於擁有很多重複部分,可以進行框架結構代碼精簡。我後來精簡代碼可以參見我的cnblogs文章: