1. 程式人生 > >jquery實現的一個網頁飄窗小外掛

jquery實現的一個網頁飄窗小外掛

//定義外掛 !function($){ /** * Description: jquery飄窗外掛,可自適應瀏覽器寬高的變化 * Author: YZCS * CreateTime: 2015-04-25 * param: args={startL:default, startT:default, angle:-Math.PI/4, speed: 125} * 引數說名: startL飄窗初始時距離左邊的距離, startT飄窗初始化距離頂部的距離, angle飄窗初始運動方向, speed運動速度(px/s) * CopyRight: GPL */
$.fn.autoMove = function(args){ //先定義一些工具函式判斷邊距 function isTop(pos, w_w, w_h, d_w, d_h){//飄窗到達上邊距 if(pos.top<=0){ return true; }else{ return false; } } function
isBottom(pos, w_w, w_h, d_w, d_h){
//飄窗到達下邊距 if(pos.top>=(w_h-d_h)){ return true; }else{ return false; } } function isLeft(pos, w_w, w_h, d_w, d_h){//飄窗到達左邊距 if(pos.left<=0
){ return true; }else{ return false; } } function isRight(pos, w_w, w_h, d_w, d_h){//飄窗到達右邊距 if(pos.left>=(w_w-d_w)){ return true; }else{ return false; } } return this.each(function(){ var w_w = parseInt($(window).width()), w_h = parseInt($(window).height()), d_w = parseInt($(this).width()), d_h = parseInt($(this).height()), d_l = (w_w-d_w)/2, d_t = (w_h-d_h)/2, max_l = w_w - d_w; max_t = w_h - d_h; //位置及引數的初始化 var setobj = $.extend({startL:d_l, startT:d_t, angle:Math.PI/4, speed:100}, args); $(this).css({position: 'absolute', left: setobj['startL']+'px', top: setobj['startT']+'px'}); var position = {left: setobj['startL'], top: setobj['startT']};//飄窗位置物件 var that = $(this); var angle= setobj.angle; var time = 10;//控制飄窗運動效果,值越小越細膩 var step = setobj.speed * (time/1000);//計算運動步長 var decoration = {x:step*Math.cos(angle), y:step*Math.sin(angle)};//計算二維上的運動增量 var mvtid; $(window).on('resize', function(){//視窗大小變動時重新設定運動相關引數 w_w = parseInt($(window).width()), w_h = parseInt($(window).height()), max_l = w_w - d_w; max_t = w_h - d_h; }); function move(){ position.left += decoration.x; position.top += decoration.y; if(isLeft(position, w_w, w_h, d_w, d_h)||isRight(position, w_w, w_h, d_w, d_h)){ decoration.x = -1*decoration.x; } if(isRight(position, w_w, w_h, d_w, d_h)){ position.left = max_l; } if(isTop(position, w_w, w_h, d_w, d_h)||isBottom(position, w_w, w_h, d_w, d_h)){ decoration.y = -1*decoration.y; } if(isBottom(position, w_w, w_h, d_w, d_h)){ position.top = max_t; } //that.css({left:position.left, top:position.top}); that.animate({left:position.left, top:position.top}, time);//改用jquery動畫函式使其更加平滑 mvtid = setTimeout(move, time);//遞迴呼叫,使飄窗連續運動 } move();//觸發動作 that.on('mouseenter', function(){ clearTimeout(mvtid) });//新增滑鼠事件 that.on('mouseleave', function(){ move() }); }); }//end plugin definition }(jQuery);