//广告漂浮窗口 function floatad(selector) { var obj = $(selector); if (obj.find(".flbox").length == 0) return;//如果没有内容,不执行 var windowheight = $(window).height();//浏览器高度 var windowwidth = $(window).width();//浏览器宽度 var dirx = -1.5;//每次水平漂浮方向及距离(单位:px),正数向右,负数向左,如果越大的话就会看起来越不流畅,但在某些需求下你可能会需要这种效果 var diry = -1;//每次垂直漂浮方向及距离(单位:px),正数向下,负数向上,如果越大的话就会看起来越不流畅,但在某些需求下你可能会需要这种效果 var delay = 30;//定期执行的时间间隔,单位毫秒 obj.css({ left: windowwidth / 2 - obj.width() / 2 + "px", top: windowheight / 2 - obj.height() / 2 + "px" });//把元素设置成在页面中间 obj.show();//元素默认是隐藏的,避免上一句代码改变位置视觉突兀,改变位置后再显示出来 var handler = setinterval(move, delay);//定期执行,返回一个值,这个值可以用来取消定期执行 obj.hover(function() {//鼠标经过时暂停,离开时继续 clearinterval(handler);//取消定期执行 }, function() { handler = setinterval(move, delay); }); obj.find(".flclose").click(function() {//绑定关闭按钮事件 close(); }); $(window).resize(function() {//当改变窗口大小时,重新获取浏览器大小,以保证不会过界(飘出浏览器可视范围)或漂的范围小于新的大小 windowheight = $(window).height();//浏览器高度 windowwidth = $(window).width();//浏览器宽度 }); function move() {//定期执行的函数,使元素移动 var currentpos = obj.position();//获取当前位置,这是jquery的函数,具体见:http://hemin.cn/jq/position.html var nextposx = currentpos.left + dirx;//下一个水平位置 var nextposy = currentpos.top + diry;//下一个垂直位置 if (nextposx <= 0 || nextposx >= windowwidth - obj.width()) {//如果达到左边,或者达到右边,则改变为相反方向 dirx = dirx * -1;//改变方向 nextposx = currentpos.left + dirx;//为了不过界,重新获取下一个位置 } if (nextposy <= 0 || nextposy >= windowheight - obj.height() - 5) {//如果达到上边,或者达到下边,则改变为相反方向。 diry = diry * -1;//改变方向 nextposy = currentpos.top + diry;//为了不过界,重新获取下一个位置 } obj.css({ left: nextposx + "px", top: nextposy + "px" });//移动到下一个位置 } function close() {//停止漂浮,并销毁漂浮窗口 clearinterval(handler); obj.remove(); } }