jQuery事件 (jQuery實現圖片輪播)


jQuery事件按執行時間,主要分為兩種,第一種是在網頁加載完執行,第二種綁定在元素中,由訪問者某些行為觸發。

 

$(document).ready(function(){
   //事件
});
$("#xx").bind(  "click",function(){
   //事件
});
$("#xx").unbind("click");  //接觸該元素的所有click事件

當然,第二種事件一般情況下是放在第一種內部的

事件的簡寫

$("#xx").click(function(){
 //事件
});

jQuery還提供了一些合成事件,簡化代碼

hover(enter,leave);//光標移動到某位置,觸發enter事件,離開觸發leave事件
toggle(fn1,fn2,fn3...);//鼠標連續單擊事件
$("#xx").hover(function(){
    $(this).hide();
},function{
    $(this).show();

});                             //此段代碼僅為舉例,運行效果並不好

事件冒泡的解決方法

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8"/>
   <title>example for html5</title>
   <script src="jquery.js" type="text/javascript"></script>
   
</head>

<body>


   <div id="diveve">
     <p id="peve">
       ncqnvqj<a href=# id="aeve">aeve</a>
     </p>
   </div>


<script type="text/javascript">
$(document).ready(function(){
$("#diveve").click(function(){
  alert("div");
});
$("#peve").click(function(event){
  alert("p");
  event.stopPropagation();
});
$("#aeve").click(function(event){
  alert("a");
  event.stopPropagation();
});

});

 模擬操作:trigger()

$("#xx").trigger("click");    //普通模擬

$("#xx").bind("myclick",function(){});
$("#xx").trigger("myclick");        //自定義事件

$("#xx").bind("myclick",function(event,message1,message2){});
$("#xx").trigger("myclick",["我的自定義","事件"]); //傳遞數據

 

集合以上知識點,可實現圖片的輪播動畫:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8"/>
   <title>example for html5</title>
   <script src="jquery.js" type="text/javascript"></script>
   <style type="text/css">


    .showmore{
    position:absolute;
    top:100px;
    width:300px;
    left:50%;
    margin-left:-150px;
    height:100px;
    overflow:hidden;
    display:inline-block;
    border:1px pink solid
    }
   </style>
</head>

<body>
<div><a href=# id="button">翻頁</a></div>
<div class="showmore" >

</div>
<script type="text/javascript">
$(document).ready(function(){

for(var i=1;i<5;i++)
{  

   $divpic=$("<img class='imgr'/>");
   $divpic.attr("src",String(i)+".jpg");
   $(".showmore").append($divpic);
   $divpic.css({"position":"absolute","top":"0px","left":i*100-100+"px","width":"100px","height":"100px"});
}
    $(function()
{ //把輪播函數放在匿名函數中 $(
"#button").bind("click",function() //給button綁定事件
{
$(
".imgr").animate({left:"-=100px"},function() //animate()方法中回調函數的使用 { for(var i=0;i<4;i++) //遍歷找出第一張圖片,並將其移動到盒子最后端 { if($($(".imgr")[i]).css("left")=="-100px") //這里涉及到DOM和jQuery對象的相互轉化 { $($(".imgr")[i]).css("left","300px"); } } }); }); }); }); </script> </body> </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM