jQuery動畫製作

事件的綁定
bind(type[,data],fn);
type:包括 blur/focus/load/resize/scroll/unload/click/dblclick/mousedown/error
mouseup/mousemove/mouseover/mouseout/mouseenter/mouseleave/change/select/submit/keydown/keypress/keyup等
還可以自定義名稱
data:可選參數,作爲event.data屬性值傳遞給事件對象的額外數據對象
fn:用來綁定的處理函數

例子:
 $("#panel h5.head").bind("click",function(){
        var $content = $(this).next();
        if($content.is(":visible")){
            $content.hide();
        }else{           
                         $content.show();
        }   
               }
   )

也可以這樣實現
 $("#panel h5.head").bind("mouseover",function(){
        $(this).next().show();
    });
 $("#panel h5.head").bind("mouseout",function(){
         $(this).next().hide();
    })


合成事件

hover方法
hover(enter,leave);//用於模擬光標懸停事件,當光標移動到元素上時
會觸發指定的函數enter;當光標移出這個元素時,會觸發指定的第二個函數(leave)

注意:
在IE6裏僅有超級鏈接才用僞類選擇符,對於其他元素,可以使用JQuery的hover方法
hover方法準確來說是代替bind("mouseenter")和bind("mouseleave")
當需要觸發hover函數的時候,第二個參數需要用trigger("mouseleave")來觸發


toggle()
toggle(fn1,fn2,...fnN)//用於模仿鼠標連續單擊事件,當第一次單擊元素,觸發fn1
當第二次單擊元素,觸發fn2,過了後再重新從第一個函數開始
還有一個另外的作用:切換元素的可見狀態
如果元素是可見的,單擊切換則爲隱藏,反之亦然



針對上面的例子修改爲:
 $("#panel h5.head").hover(function(){
        $(this).next().show();
    },function(){
        $(this).next().hide();
       })

  $("#panel h5.head").toggle(function(){
    $(this).next().show();
    },function(){
    $(this).next().hide();
    })

  $("#panel h5.head").toggle(function(){
    $(this).next().toggle();
    },function(){
    $(this).next().toggle();
    })

.highlight{ background:#FF3300; }

  $("#panel h5.head").toggle(function(){
            $(this).addClass("highlight");
            $(this).next().show();
    },function(){
            $(this).removeClass("highlight");
            $(this).next().hide();
    });


事件冒泡
什麼是冒泡?
頁面上有多個事件,也可以多個元素響應同一個事件
假設頁面上有兩個元素,其中一個元素嵌套在另外一個元素裏,並且都綁定了click事件,同時<body>
元素也綁定了click事件

<div id="content">   
外層div元素   
<span>內層span元素</span>
外層div元素</div>
 <div id="msg"></div>

// 爲span元素綁定click事件
    $('span').bind("click",function(){
        var txt = $('#msg').html() + "<p>內層span元素被點擊.<p/>";
        $('#msg').html(txt);
    });
// 爲div元素綁定click事件
    $('#content').bind("click",function(){
        var txt = $('#msg').html() + "<p>外層div元素被點擊.<p/>";
        $('#msg').html(txt);
    });
// 爲body元素綁定click事件
    $("body").bind("click",function(){
        var txt = $('#msg').html() + "<p>body元素被點擊.<p/>";
        $('#msg').html(txt);
    });
當點擊內部<span>元素,觸發<span>元素的cick事件時,會輸出三條記錄
而這個就是由事件冒泡引起的
引發事件順序“冒泡”
(1)<span>
(2)<div>
(3)<body>
因爲事件會按照DOM層次結構像水泡一樣不斷向上直至頂端,所以稱爲冒泡


停止冒泡的方法如下:

$('span').bind("click",function(event){
    var txt = $('#msg').html() + "<p>內層span元素被點擊.<p/>";
    $('#msg').html(txt);
    event.stopPropagation();    //  阻止事件冒泡
    });

阻止默認行爲

什麼叫默認行爲?
網頁中的元素有自己默認的行爲,例如,單擊超鏈接後會跳轉、單擊提交按鈕後表單會提交
而有時需要阻止默認行爲的執行


阻止提交按鈕
 $("#sub").bind("click",function(event){
        var username = $("#username").val();  //獲取元素的值
         if(username==""){     //判斷值是否爲空   
         $("#msg").html("<p>文本框的值不能爲空.</p>");  //提示信息
             event.preventDefault();  //阻止默認行爲 ( 表單提交 )
         }
  })

如果需要既屏蔽默認行爲又屏蔽冒泡,則用return false 即可



事件捕獲
事件捕獲是從最上到最下的過程,Jquery不支持事件捕獲,用原生的javascript即可

事件對象的屬性

event.type()
$("a").click(function(event) {
      alert(event.type);//獲取事件類型
      return false;//阻止鏈接跳轉
    });

event.preventDefault() //阻止默認行爲

event.stopPropagation()//不允許事件冒泡

event.target()
$("a[href=http://google.com]").click(function(event) {
      alert(event.target.href);//獲取觸發事件的<a>元素的href屬性值
      return false;//阻止鏈接跳轉
    });

event.relatedTarget()

event.pageX()
$("a").click(function(event) {
 alert("Current mouse position: " + event.pageX + ", " + event.pageY );//獲取鼠標當前相對於頁面的座標   
  return false;//阻止鏈接跳轉
    });

e.which()
$("a").mousedown(function(e){
        alert(e.which)  // 1 = 鼠標左鍵 left; 2 = 鼠標中鍵; 3 = 鼠標右鍵
        return false;//阻止鏈接跳轉

});


$("input").keyup(function(e){
        alert(e.which);//得到輸入框內的asciii碼
    })

e.metaKey
$("input").keyup(function(e){
        alert(e.metaKey +" "+e.ctrlKey );
        $(this).blur();   
})

event.originalEvent()
指向原始的事件對象



移除事件
unbind([type][,data]);
type爲事件類型
data爲將要移除的函數

如果沒有參數,則刪除所有綁定的事件
如果提供了事件類型作爲參數,則只刪除該類型的綁定事件
例子:

  $('#btn').unbind("click");})


 $('#btn').bind("click", myFun1 = function(){                     $('#test').append("<p>我的綁定函數1</p>");              }).           

     $('#test').append("<p>我的綁定函數1</p>");});
 $('#delTwo').click(function(){   
          $('#btn').unbind("click",myFun2);
       });


 $('#btn').one("click", myFun1 = function(){//只有第一次單擊纔有效,第二次無效                     $('#test').append("<p>我的綁定函數1</p>");       

      }).$('#test').append("<p>我的綁定函數1</p>");});


模擬操作

1.常用模擬

$('#btn').trigger("click");//自動觸發btn的click事件

2.觸發自定義事件

   $('#btn').bind("myClick", function(){
      $('#test').append("<p>我的自定義事件.</p>");
   });
       $('#btn').click(function(){   
        $(this).trigger("myClick");
       }).trigger("myClick");


 $('#btn').bind("myClick", function(event, message1, message2){
   $('#test').append( "<p>"+message1 + message2 +"</p>");
        });
  $('#btn').click(function(){
   $(this).trigger("myClick",["我的自定義","事件"]);
       }).trigger("myClick",["我的自定義","事件"]);//給自定義事件傳遞參數


3.執行默認操作
<button id="old">trigger</button>
<button id="new">triggerHandler</button>
<input />

 $('#old').bind("click", function(){
   $("input").trigger("focus");    //觸發input元素的focus事件,也會使input獲取輸入焦點
    });
 $('#new').bind("click", function(){
   $("input").triggerHandler("focus");////僅僅觸發input元素的focus事件
        });
 $("input").focus(function(){ 
    $("body").append("<p>focus.</p>");})

4.綁定多個事件類型
$(function(){
$("div").bind("mouseover mouseout",fuction(){$(this).toggleClass("over");})

});


5.添加事件命名空間,便於管理
  $(function(){    $("div").bind("click.plugin",function(){
           $("body").append("<p>click事件</p>");    });
    $("div").bind("mouseover.plugin", function(){
           $("body").append("<p>mouseover事件</p>");
    });
    $("div").bind("dblclick", function(){
           $("body").append("<p>dblclick事件</p>");
    });
    $("button").click(function() {
        $("div").unbind(".plugin");
      })
  })

6.相當事件名稱,不同命名空間執行方法
 $(function(){    $("div").bind("click",function(){
           $("body").append("<p>click事件</p>");
    });
    $("div").bind("click.plugin", function(){
           $("body").append("<p>click.plugin事件</p>");
    });
    $("button").click(function() {
          $("div").trigger("click!");    // 注意click後面的感嘆號匹配所有不包含在命名空間中的命名方法
    });
  })
而如果都要被觸發,可以寫爲 $("div").trigger("click"); 



動畫
注意:用jquery做動畫效果必須在文件頭部包含如下的DTD定義,否則可能會引起動畫的抖動
      Jquery任何動畫效果都可以指定三種速度參數,slow(0.6秒) normal(0.4秒) fast(0.2秒)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


1.show()和hide()方法//改變的是元素的display屬性

 $("#panel h5.head").toggle(function(){
         $(this).next().hide(600);
    },function(){
         $(this).next().show(600);//600可以寫爲slow(600秒內完成)/normal(400秒內完成)/fast(200秒內完成)
    })

2.fadeOut()和fadeIn()//改變元素的透明度,直到dispaly爲none或者爲block爲止
$(function(){
    $("#panel h5.head").toggle(function(){
         $(this).next().fadeOut();
    },function(){
         $(this).next().fadeIn();//
    })
})

3.slideUp()和slideDown()//改變元素的高度
$(function(){
    $("#panel h5.head").toggle(function(){
         $(this).next().slideUp();
    },function(){
         $(this).next().slideDown();//當遇到一個display爲none時,方法會將元素由上至下延伸顯示
    })
})
4.自定義動畫方法
animated (params,speed,callback);
params:一個包含樣式屬性及值的映射,比如{property1:"value1",peroperty2:"value2",...}
speed :速度參數
callback:在動畫完成時執行的參數,可選

1.例子:
#panel {position: relative; width: 100px; height:100px;border: 1px solid #0050D0;background: #96E555; cursor: pointer}//前提是必須設置爲position: relative;或者爲

absolute
<div id="panel"></div>
$(function(){
    $("#panel").click(function(){
       $(this).animate({left: "500px"}, 3000);
    })
})

2.累加累減動畫
上面的也可以寫爲
  $(this).animate({left: "+=500px"}, 3000);
  $(this).animate({left: "-=500px"}, 3000);

3.多重動畫
(1)同時執行多個動畫
$(this).animate({left: "500px",height:"200px"}, 3000);//既向右滑動,並且放大元素的高度

(2)按順序執行多個動畫
$(function(){
    $("#panel").click(function(){
         $(this).animate({left: "500px"}, 3000).animate({height: "200px"}, 3000);//將先向右然後再增大高度,這也叫動畫隊列
    })
})
4.綜合動畫

    $(function(){
       // $("#panel").css("opacity", "0.5");//設置不透明度
        $("#panel").click(function(){
              $(this).animate({left: "400px", height:"200px" ,opacity: "1"}, 3000)
                     .animate({top: "200px" , width :"200px"}, 3000 )
                     .fadeOut("slow");
        });
    });

$("#panel").click(function(){
              $(this).animate({left: "400px", height:"200px" ,opacity: "1"}, 3000)
                     .animate({top: "200px" , width :"200px"}, 3000 ,function(){
                         $(this).css("border","5px solid blue");
                     })
                     
        });
注意:假如把css方法放到第一個參數後面,將導致動畫一開始就執行CSS方法,因爲CSS方法不參與動畫隊列



停止動畫

stop方法
stop([clearQueue][,gotoEnd])
clearQueue和gotoEnd都是可選參數
clearQueue:是否要清空未執行完的動畫隊列
gotoEnd:是否直接將正在執行的動畫跳轉到末狀態

stop(true,true)//停止當前動畫並直接到達當前動畫的末狀態並清空動畫隊列


2.判斷元素是否處於動畫狀態
要避免動畫累積而導致的動畫於行爲的不一致。
if (!$(element).is(":animated"))//判斷元素是否正處於動畫狀態
{
//如果當前沒有進行動畫,則添加新動畫

3.其他動畫方法
toggle() //切換元素的可見狀態
slideToggle()//通過高度變化來切換匹配元素的可見性
fadeTo()
}

實例:
<script type="text/javascript">
$(function(){
    var page = 1;
    var i = 4; //每版放4個圖片
    //向後 按鈕
    $("span.next").click(function(){    //綁定click事件
         var $parent = $(this).parents("div.v_show");//根據當前點擊元素獲取到父元素
         var $v_show = $parent.find("div.v_content_list"); //尋找到“視頻內容展示區域”
         var $v_content = $parent.find("div.v_content"); //尋找到“視頻內容展示區域”外圍的DIV元素
         var v_width = $v_content.width() ;
         var len = $v_show.find("li").length;
         var page_count = Math.ceil(len / i) ;   //只要不是整數,就往大的方向取最小的整數
         if( !$v_show.is(":animated") ){    //判斷“視頻內容展示區域”是否正在處於動畫
              if( page == page_count ){  //已經到最後一個版面了,如果再向後,必須跳轉到第一個版面。
                $v_show.animate({ left : '0px'}, "slow"); //通過改變left值,跳轉到第一個版面
                page = 1;
                }else{
                $v_show.animate({ left : '-='+v_width }, "slow");  //通過改變left值,達到每次換一個版面
                page++;
             }
         }
         $parent.find("span").eq((page-1)).addClass("current").siblings().removeClass("current");
   });
    //往前 按鈕
    $("span.prev").click(function(){
         var $parent = $(this).parents("div.v_show");//根據當前點擊元素獲取到父元素
         var $v_show = $parent.find("div.v_content_list"); //尋找到“視頻內容展示區域”
         var $v_content = $parent.find("div.v_content"); //尋找到“視頻內容展示區域”外圍的DIV元素
         var v_width = $v_content.width();
         var len = $v_show.find("li").length;
         var page_count = Math.ceil(len / i) ;   //只要不是整數,就往大的方向取最小的整數
         if( !$v_show.is(":animated") ){    //判斷“視頻內容展示區域”是否正在處於動畫
              if( page == 1 ){  //已經到第一個版面了,如果再向前,必須跳轉到最後一個版面。
                $v_show.animate({ left : '-='+v_width*(page_count-1) }, "slow");
                page = page_count;
            }else{
                $v_show.animate({ left : '+='+v_width }, "slow");
                page--;
            }
        }
        $parent.find("span").eq((page-1)).addClass("current").siblings().removeClass("current");
    });
});


</script>


<div class="v_show">
    <div class="v_caption">
        <h2 class="cartoon" title="卡通動漫">卡通動漫</h2>
        <div class="highlight_tip">
            <span class="current">1</span><span>2</span><span>3</span><span>4</span>
        </div>
        <div class="change_btn">
            <span class="prev" >上一頁</span>
            <span class="next">下一頁</span>
        </div>
        <em><a href="#">更多>></a></em>
    </div>
    <div class="v_content">
        <div  class="v_content_list">
            <ul>
                <li><a href="#"><img src="img/01.jpg" alt="海賊王" /></a><h4><a href="#">海賊王</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/01.jpg" alt="海賊王" /></a><h4><a href="#">海賊王</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/01.jpg" alt="海賊王" /></a><h4><a href="#">海賊王</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/01.jpg" alt="海賊王" /></a><h4><a href="#">海賊王</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/02.jpg" alt="哆啦A夢" /></a><h4><a href="#">哆啦A夢</a></h4><span>播放:<em>33,326</em></span></li>
                <li><a href="#"><img src="img/02.jpg" alt="哆啦A夢" /></a><h4><a href="#">哆啦A夢</a></h4><span>播放:<em>33,326</em></span></li>
                <li><a href="#"><img src="img/02.jpg" alt="哆啦A夢" /></a><h4><a href="#">哆啦A夢</a></h4><span>播放:<em>33,326</em></span></li>
                <li><a href="#"><img src="img/02.jpg" alt="哆啦A夢" /></a><h4><a href="#">哆啦A夢</a></h4><span>播放:<em>33,326</em></span></li>
                <li><a href="#"><img src="img/03.jpg" alt="火影忍者" /></a><h4><a href="#">火影忍者</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/03.jpg" alt="火影忍者" /></a><h4><a href="#">火影忍者</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/03.jpg" alt="火影忍者" /></a><h4><a href="#">火影忍者</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/03.jpg" alt="火影忍者" /></a><h4><a href="#">火影忍者</a></h4><span>播放:<em>28,276</em></span></li>
                <li><a href="#"><img src="img/04.jpg" alt="龍珠" /></a><h4><a href="#">龍珠</a></h4><span>播放 <em>57,865</em></span></li>
                <li><a href="#"><img src="img/04.jpg" alt="龍珠" /></a><h4><a href="#">龍珠</a></h4><span>播放 <em>57,865</em></span></li>
                <li><a href="#"><img src="img/04.jpg" alt="龍珠" /></a><h4><a href="#">龍珠</a></h4><span>播放 <em>57,865</em></span></li>
                <li><a href="#"><img src="img/04.jpg" alt="龍珠" /></a><h4><a href="#">龍珠</a></h4><span>播放 <em>57,865</em></span></li>
             </ul>
        </div>
    </div>
</div>

* { margin:0; padding:0; word-break:break-all; }
body { background:#FFF; color:#333; font:12px/1.5em Helvetica, Arial, sans-serif; }
h1, h2, h3, h4, h5, h6 { font-size:1em; }
a { color:#2B93D2; text-decoration:none; }
a:hover { color:#E31E1C; text-decoration:underline; }
ul, li { list-style:none; }
fieldset, img { border:none; }

/* v_show style */
.v_show { width:595px; margin:20px 0 1px 60px; }
.v_caption { height:35px; overflow:hidden; background:url(img/btn_cartoon.gif) no-repeat 0 0; }
.v_caption h2 { float:left; width:84px; height:35px; overflow:hidden; background:url(img/btn_cartoon.gif) no-repeat; text-indent:-9999px; }
.v_caption .cartoon { background-position: 0 -100px; }
.v_caption .variety { background-position:-100px -100px; }
.highlight_tip { display:inline; float:left; margin:14px 0 0 10px; }
.highlight_tip span { display:inline; float:left; width:7px; height:7px; overflow:hidden; margin:0 2px; background:url(img/btn_cartoon.gif) no-repeat 0 -320px; text-

indent:-9999px; }
.highlight_tip .current { background-position:0 -220px; }
.change_btn { float:left; margin:7px 0 0 10px; }
.change_btn span { display:block; float:left; width:30px; height:23px; overflow:hidden; background:url(img/btn_cartoon.gif) no-repeat; text-indent:-9999px;

cursor:pointer; }
.change_btn .prev { background-position:0 -400px;  }
.change_btn .next { width:31px; background-position:-30px -400px; }
.v_caption em { display:inline; float:right; margin:10px 12px 0 0; font-family:simsun; }
.v_content { position:relative; width:592px; height:160px; overflow:hidden; border-right:1px solid #E7E7E7; border-bottom:1px solid #E7E7E7; border-left:1px solid

#E7E7E7; }
.v_content_list { position:absolute; width:2500px;top:0px; left:0px; }
.v_content ul {float:left;}
.v_content ul li { display:inline; float:left; margin:10px 2px 0; padding:8px; background:url(img/v_bg.gif) no-repeat; }
.v_content ul li a { display:block; width:128px; height:80px; overflow:hidden; }
.v_content ul li img {  width:128px; height:96px; }
.v_content ul li h4 { width:128px; height:18px; overflow:hidden; margin-top:12px; font-weight:normal; }
.v_content ul li h4 a { display:inline !important; height:auto !important; }
.v_content ul li span { color:#666; }
.v_content ul li em { color:#888; font-family:Verdana; font-size:0.9em; }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章