DIV CSS 佈局教程網

jQuery 事件與動畫總整理:bind、toggle、事件冒泡與表單元件實戰
編輯:JQuery特效代碼     

這份筆記把 jQuery 的事件模型與動畫 API 一次梳理,從 bind() 的三個參數講起,一路涵蓋 toggle、事件冒泡、移除與模擬事件,最後用複選框、下拉選單、表格三個元件把技巧串起來。

一、bind() 與顯示隱藏

<script src="script/jquery-1.7.1.min.js"></script>
<script>
$(function () {
  $("#divid h5.head").bind("click", function () {
    alert($(this).text());
  });
  $("#divid h5.content").css("display", "none"); // 用 css() 動態設定樣式
});

// 以 bool 變數切換顯示狀態
$(function () {
  $("#btnid").bind("click", function () {
    if (bool == true) {
      $("#btnid .content").css("display", "none");
      bool = false;
      $(this).val("顯示");
    } else {
      $("#btnid .content").css("display", "");
      bool = true;
      $(this).val("隱藏");
    }
  });
});

// 改用 is(":visible") 判斷,不必自己維護狀態變數
$(function () {
  $("input[type=button]").bind("click", function () {
    var content = $("#divid .content");
    if (content.is(":visible")) {
      content.hide();
      $(this).val("顯示");
    } else {
      content.show();
      $(this).val("隱藏");
    }
  });
});
</script>>

<body>
<div id="divid">
  <h5 class="head">Rocky?</h5>
  <div class="content">就讓雨下下來 不用帶傘 讓一切完蛋 看被淋濕的心 多久才會曬干</div>
</div>
<input type="button" name="name" value="顯示 " id="btnid" />
</body>

bind() 的完整形式是 bind(type, data, handler):第一個參數是事件名稱(click、dblclick、mouseover 等),第二個是會傳進事件處理函式的資料物件,第三個是處理函式本身。

至於顯示隱藏,還沒學 show()/hide() 之前得自己維護一個 boolean 變數來記狀態,按鈕文案還要跟著改,寫起來頗囉唆。改用 is(":visible") 直接問元素目前的狀態,程式碼立刻清爽。

二、toggle() 與事件冒泡

<script>
$(function () {
  $("input[type=button]").toggle(function () {   // 兩個參數都是事件,輪番觸發
    $(this).css("backgroundColor", "red");
  }, function () {
    $(this).css("backgroundColor", "yellow");
  });
});

$(function () {
  $("div").each(function () {
    $(this).bind("mouseup", function (e) {
      alert(e.pageX);  // 滑鼠 X 座標
      alert(e.pageY);  // 滑鼠 Y 座標
      alert(e.which);  // 1=左鍵, 2=滾輪, 3=右鍵
    });
  });
});

$(function () {
  $("#txt").keydown(function (e) {
    e.preventDefault();      // 阻止預設行為
    alert(e.keyCode);        // 取得按下的鍵碼
  });
});

// 事件冒泡:點內層 div,外層 div 也會收到 click
$(function () {
  $("#ouuerdiv").click(function () { alert($(this).text()); });
  $("#div").click(function () { alert($(this).text()); });
  $("#innerdiv").click(function () { alert($(this).text()); });
});
</script>

<body>
<input type="button" name="btnname" value="按鈕" id="btn"/>
<div id="ouuerdiv">外部div<div id="div">中部div<div id="innerdiv">內部div</div></div></div>
<a href="https://www.baidu.com" id="a">百度</a>
<textarea id="txt" rows="5" cols="5"></textarea>
</body>

toggle 事件:連續掛上多個函式時,jQuery 會依點擊次數輪流執行,常用來做「點一下變色、再點一下變回來」的兩態切換。

事件冒泡:頁面上可以有多個元素監聽同一種事件。若 div 巢狀在另一個 div 裡且兩者都綁了 click,點內層時外層也會被觸發。很多人會想「我只點了內層啊」,這就是冒泡。要阻止的話,用 event.stopPropagation() 阻擋傳遞,用 event.preventDefault() 取消預設行為(例如 <a> 的跳轉),兩者用途不同,別搞混。

三、移除事件與連續綁定

<script>
$(function () {
  $("removeall").click(function () {
    $("#btn").unbind();   // 移除所有事件
  });

  $("#btn").bind("click", function () {
      $("#text").append("<p>我是第一個添加的事件</p>")
    })
    .bind("click", function () {
      $("#text").append("<p>我是第二個添加的事件</p>")
    })
    .bind("click", function () {
      $("#text").append("<p>我是第三個添加的事件</p>")
    });
});
</script>

<body>
<button id="btn">單擊我吧</button><button id="removeall">刪除所有的事件</button>
<div id="text">div文本信息</div>
</body>

bind() 負責掛上,unbind() 負責拆掉。想一次掛多個事件,靠鏈式接續呼叫 .bind() 即可,三個函式會依序執行。若要精準移除,unbind('click', 特定函式) 可以把參考名稱傳進去,只拆掉那一個。

四、模擬事件

bind、click 這些通常要使用者真的點擊才會觸發。但有時候我們希望「頁面載入後自動執行一次點擊效果」,這時就用 trigger() 主動觸發,不必等使用者操作。

五、其他常用動畫方法

<script>
$(function () {
  $("#btn").click(function () {
    // $("#div").hide(2000);    // 2 秒內隱藏
    // $("#div").show(2000);    // 2 秒內顯示
    // $("#div").fadeIn(2000);  // 提高不透明度直到完全顯示
    // $("#div").fadeOut(2000); // 降低不透明度直到消失
    // $("div").fadeTo(600, 0.2); // 0.6 秒內把透明度變為 0.2

    $("#btn").toggle(function () {
      $("div").slideDown(2000);   // 改高度,由上往下展開
      $(this).val("顯示")
    }, function () {
      $("div").slideUp(2000);     // 改高度,由下往上收起
      $(this).val("隱藏")
    });
  });
});
</script>

<body>
<div id="div" style="width:300px; height:300px;">1234</div>
<input type="button" name="name" value="操作動畫" id="btn" />
</body>

這幾個方法都接受 duration 參數。差別在動的是什麼屬性:show/hide 同時動寬高與透明度、slideUp/slideDown 只動高度、fadeIn/fadeOut 只動透明度、fadeTo 則可指定目標透明度。

六、多行文字框的高度變化

<script src="script/jquery-1.7.1.min.js"></script>
<style>
input:focus, textarea:focus { border: 1px solid #f00; }
</style>
<script>
$(function () {
  var comment = $("#comment");
  $(".bigger").click(function () {
    if (comment.height() < 500) {
      comment.height(comment.height() + 100); // 每次加高 100
    }
  });
  $(".smaller").click(function () {
    if (comment.height() > 100) {
      comment.height(comment.height() - 100); // 每次降低 100
    }
  });
});
</script>

<body>
<form action="#" method="post" id="regform">
  <div class="msg"><span class="bigger">放大</span><span class="smaller">縮小</span></div>
  <div><textarea rows="8" cols="20" id="comment">海海海海</textarea></div>
</form>
</body>

用 .height() 讀取當前高度再增減,並夾在上下限之間,就得到最樸素的「放大/縮小」效果。若想要平滑過渡,把 .height() 換成 .animate({ height: 值 }) 即可。

七、複選框:全選、全不選、反選

<script>
$(function () {
  $("#checkall").bind("click", function () {
    $(":checkbox").each(function () {
      $(this).attr("checked", "checked");
    });
  });
  $("#checkno").bind("click", function () {
    $(":checkbox").attr("checked", false);
  });
  $("#checkRev").bind("click", function () {
    $(":checkbox").each(function () {
      if ($(this).attr("checked") == "checked") {
        $(this).attr("checked", false);
      } else {
        $(this).attr("checked", true);
      }
    });
  });
});
</script>

<body>
<form>你愛好的運動?<br />
<input type="checkbox" name="names" value="足球 " />足球<br />
<input type="checkbox" name="names" value="籃球 " />籃球<br />
<input type="checkbox" name="names" value="排球 " />排球<br />
<input type="checkbox" name="names" value="羽毛球 " />羽毛球<br />
<input type="button" id="checkall" value="全選 " /><br />
<input type="button" id="checkno" value="全不選 " /><br />
<input type="button" id="checkRev" value="反選 " /><br />
<input type="button" name="send" value="提交" /><br />
</form>
</body>

反選其實可以壓縮成一行:$(this).prop("checked", !$(this).prop("checked"))。

要特別注意的是,勾選狀態屬於「目前狀態」而非「初始屬性」,在 jQuery 1.6 之後必須用 .prop('checked') 讀寫;用 .attr() 在新版 jQuery 上不會得到正確結果。

八、下拉選單:把選項搬到另一邊

<script>
$(function () {
  $("#add").click(function () {
    var selectoption = $("#select1 option:selected");
    selectoption.remove();
    selectoption.appendTo('#select2'); // 把選中項加入右側 select
  });

  $("#addAll").bind("click", function () {
    $("#select1 option").appendTo('#select2');
  });
});
</script>

<body>
<div class="center">
  <select multiple="multiple" id="select1" style="width: 100px; height: 160px">
    <option value="1">選項1</option><option value="2">選項2</option>
    <option value="3">選項3</option><option value="4">選項4</option>
    <option value="5">選項5</option><option value="6">選項6</option>
    <option value="7">選項7</option><option value="8">選項8</option>
    <option value="9">選項9</option>
  </select>
  <div>
    <span id="add">添加到右邊</span>
    <span id="addAll">全部添加到右邊</span>
  </div>
</div>

<div class="center" style="float:right">
  <select multiple="multiple" id="select2" style="width: 100px; height: 160px"></select>
</div>
</body>

關鍵在於 appendTo() 是「搬移」而非複製——同一個 option 節點被掛到新的 select 下,原本的位置自然空了,所以 remove() 嚴格說並非必要,加上只是語意更明確。要改成複製才對嗎?那就用 .clone().appendTo()。

九、表格:斑馬線與點擊高亮

<script src="script/jquery-1.3.2.min.js"></script>
<style>
.odd { background-color: #ffffee; }
</style>
<script>
$("#table tr:odd").addClass("odd");              // 索引為奇數的列
$("#table tr:even:not(:first)").addClass("even"); // 偶數列,排除表頭
$("table tr").each(function () {
  $(this).click(function () {
    $(this).css("backgroundColor", "red").siblings().css("backgroundColor", "");
  });
});
</script>

<body>
<table border="1" id="table">
<thead><tr><th>姓名</th><th>性別</th><th>暫住地</th></tr></thead><tbody>
<tr class="parent" id="row1"><td colspan="3">前台設計組</td></tr>
<tr class="child1"><td>張三</td><td>男</td><td>浙江寧波</td></tr>
<tr class="child1"><td>李四</td><td>女</td><td>浙江杭州</td></tr>
<tr class="parent" id="row2"><td colspan="3">前台開發組</td></tr>
<tr class="child2"><td>王五</td><td>男</td><td>湖南長沙</td></tr>
<tr class="child2"><td>趙六</td><td>男</td><td>湖南長沙</td></tr>
<tr class="parent" id="row3"><td colspan="3">後台開發組</td></tr>
<tr class="child3"><td>孫七</td><td>男</td><td>湖南長沙</td></tr>
<tr class="child3"><td>周八</td><td>男</td><td>湖南長沙</td></tr>
</tbody>
</table>
</body>

:odd/:even 搭配 addClass() 做斑馬線是最經典的應用;:not(:first) 則用來跳過表頭。點擊高亮那段的巧思在 .siblings()——先把其他列的背景清空,再設定自己,就實現了「單選」的視覺效果。

若表格有分組標題列(如範例中的 class="parent"),實務上通常會再排除這些列,避免斑馬線套到合併儲存格上顯得凌亂。

小結

這批 API 的老面孔(bind、unbind、live、die、delegate)在新版 jQuery 中已被 on()/off() 整合取代,toggle(fn, fn) 這種事件切換寫法也已在 jQuery 1.9 移除。新專案建議直接採用 on(),並善用事件委派 $(document).on('click', '.selector', fn) 一次解決動態元素的綁定問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved