DIV CSS 佈局教程網

用 jQuery UI 的 shake 效果讓元素震動:原理、參數與完整範例
編輯:JQuery特效代碼     

想讓頁面上某些區塊抓住讀者目光——例如促銷標語、廣告圖或提醒標示——「震動」是個便宜又有效的手法。以下示範如何用 jQuery 與 jQuery UI 實作。

一、準備一個待震的元素

可以是圖片,也可以是 div、span 等一般元素,替它取個 id(這裡叫 shake,名稱可自訂):

<img src="https://jqueryui.com/jquery-wp-content/themes/jquery/images/logo-jquery-ui.png" id="shake"/>

二、effect() 是關鍵

jQuery UI 並沒有現成的「震動」函式,要透過通用的 effect() 來呼叫:

effect('shake', options, speed);

options 有三個可用參數:

  • times:震動次數。
  • distance:震動幅度。
  • direction:震動方向。

三、實作:震三下、每 500ms 觸發一次

function interval() {
  $('#shake').effect('shake', { times: 3 }, 100);
}

$(document).ready(function() {
  var shake = setInterval(interval, 500);
});

別忘了載入 jQuery UI(這裡用 1.10.0 版):

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

四、完整可執行範例

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script>
function interval() {
  $('#shake').effect('shake', { times: 3 }, 100);
}
$(document).ready(function() {
  var shake = setInterval(interval, 500);
});
</script>
<style>
body { background: #F9F9F9; }
h1 {
  text-align: center;
  top: 30px;
  position: relative;
  font-size: 36px;
  line-height: 40px;
  margin: 0;
  font-weight: 300;
  color: #C91622;
  padding: 5px 0px;
  text-shadow: 1px 1px 0px #F2F2F2, 1px 2px 0px #B1B1B2;
  font-family: 'KenyanCoffeeRg-Regular';
  height: 70px;
}
.container {
  display: table;
  width: 50%;
  border-collapse: collapse;
  margin: 0 auto;
}
.container img { width: 253px; }
</style>
<title>jQuery Shake Effect</title>
</head>
<body>
<h1>jQuery Shake Effect</h1>
<br/><br/><br/>
<div class="container">
<img src="https://jqueryui.com/jquery-wp-content/themes/jquery/images/logo-jquery-ui.png" id="shake"/>
</div>
</body>
</html>

實務提醒:震動屬於高干擾性的動畫,不建議長時間反覆播放,也不要在有「減少動態效果」偏好設定的使用者環境中強行觸發。用一次引起注意即可,效果反而更好。

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