<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <title> new document </title> <meta name="generator" content="editplus"> <meta name="author" content=""> <meta name="keywords" content=""> <meta name="description" content=""> <script type="text/javascript"> window.onload=function(){ //写入 var oneinner = document.createelement("div"); oneinner.setattribute("style","background:#663398;position:absolute;width:100px;height:100px;border:solid 3px #2f74a7;cursor:pointer;"); var onebutton = document.createelement("input"); onebutton.setattribute("type","button"); onebutton.setattribute("value","x"); if (onebutton.style.cssfloat) { onebutton.style.cssfloat="right" } else {onebutton.style.stylefloat="right"} oneinner.appendchild(onebutton); document.body.appendchild(oneinner); //定时器 var a1a = setinterval(moves,100); //函数 var x = 10; var y = 10; function moves(){ var tops = oneinner.offsettop var lefts = oneinner.offsetleft if (lefts>=document.documentelement.clientwidth-oneinner.offsetwidth||lefts<=0) { x=-x } if (tops>=document.documentelement.clientheight-oneinner.offsetheight||tops<=0) { y=-y } tops+=y; lefts+=x; oneinner.style.top=tops+"px" oneinner.style.left=lefts+"px" } //悬停停止 oneinner.onmouseover=function(){ clearinterval(a1a); } //放手继续运动 oneinner.onmouseout=function(){ a1a =setinterval(moves,100); } //删除 onebutton.onclick=function(){ document.body.removechild(oneinner); } } </script> </head> <body> </body> </html>
jquery方法:
<!doctype html> <html> <head> <title></title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="http://www.jb51.net/workspace/js/jquery-1.7.min.js"></script> <script> $(function(){ //写入div $("<div/>",{id:"movewindow"}).css({width:"200px",height:"200px",border:"solid 3px #2f74a7",background:"#663398",position:"absolute",cursor:"pointer"}).appendto("body"); //写入关闭按钮 $("<div/>",{id:"removemw"}).css({width:"20px",height:"20px",background:"red",float:"right"}).appendto("#movewindow"); //定时器 var move = setinterval(moves,100); var x= 10; var y= 10; function moves (){ var mw = $("#movewindow").offset(); var lefts =mw.left; var tops = mw.top; if (lefts>=$(window).width()-$("#movewindow").width()||lefts<=0) { x=-x } if (tops>=$(window).height()-$("#movewindow").height()||tops<=0) { y=-y } lefts+=x; tops+=y; $("#movewindow").offset({top:tops,left:lefts}); } //悬停停止运动 $("#movewindow").mouseover(function(){ clearinterval(move); }); //移开鼠标后继续运动 $("#movewindow").mouseout(function(){ move = setinterval(moves,100); }); //点击按钮关闭 $("#removemw").click(function(){ $("#movewindow").remove(); }); }) </script> </head> <body> </body> </html>
基本思路:
1.页面加载完成之后向页面插入窗口,之后向窗口插入关闭按钮
2.使用setinterval()函数触发moves()函数开始动画
3.moves函数:首先获取当前窗口位置,之后随时间使窗口位移,每当位移到游览器边缘时反向运动
4.添加其他事件:鼠标悬停停止运动,鼠标离开继续运动,点击按钮关闭窗口
ps:不建议使用这个特效,影响用户体验
希望对你有所帮助!^_^!~~
更多js实现悬浮移动窗口(悬浮广告)的特效。