在很多的网站页面中或微信,微博都有分享到的功能。现在就编写一个简单的边侧栏。
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #div1{ width: 100px; height: 200px; background: #ccc; left: -100px; top: 70px; position: absolute; } #div1 span{ width: 20px; height: 120px; background: green; left: 100px; top: 45px; line-height: 40px; position: absolute; } </style> </head> <body> <script> window.onload = function(){ var oDiv = document.getElementById("div1"); //经过事件,速度为正 oDiv.onmouseover = function(){ startMove( 10, 0 ); } //离开事件,速度为负 oDiv.onmouseout = function(){ startMove( -10, -100); } } //运动框架 var timer = null; //两个参数iSpeed表示速度,iTartget表示目标位置 function startMove( iSpeed, iTarget){ var oDiv = document.getElementById("div1"); clearInterval( timer ); //定时器 timer = setInterval( function(){ if( oDiv.offsetLeft == iTarget ) { clearInterval( timer ); } else { //oDiv的移动 oDiv.style.left = oDiv.offsetLeft + iSpeed + "px"; } }, 30); } </script> <div id="div1"> <span>分享到</span> </div> </body> </html>
布局方面:都要使用定位。