---
title: "Jquery UI震动效果"
author: "iwebcode"
date: "2013-02-04T09:45:00Z"
tags: []
slug: "jquery-ui"
draft: false
lastmod: "2013-02-05T16:05:01Z"
id: 1791855
url: "https://iwebcode.iteye.com/blog/1791855"
---

如果你想你的博客页面某些部分引起读者的注意，你可以使这些部分震动，如广告，今天这篇文章将介绍怎样使你的页面中的元素震动起来。

要达到这个目的我们需要使用到Jquery和Jquery UI。

首先让我创建一个震动块，可以是图片，也可以是普通的dom元素，如div、span等，把元素的id命名为shake，这里可以任意命名。

我们用图片如下：

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

Jquery UI没有现成的使元素震动的方法，我们需要借助于effect方法来实现，语法如下：

```
effect('shake', options, speed);
```

参数options（这里有三个参数）：

- times：指定元素震动次数
- distance：指定元素震动幅度
- direction：指定元素震动方向

下面是具体实现方法，设置震动3次，每500ms调用一次震动：

```
function interval() {
  $('#shake').effect('shake', { times:3 }, 100);
}
$(document).ready(function() {  
  var shake = setInterval(interval, 500);    
});
```

在此之前需要先引入Jquery和Jquery UI

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

这里我引入了最新版的。

下面附上完整代码

```
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://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;
position: relative;
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="http://jqueryui.com/jquery-wp-content/themes/jquery/images/logo-jquery-ui.png" id="shake"/>
</div>
</body>
</html>
```

DEMO以及文章出自：[http://www.itlanguageexpress.info/834.html](http://www.itlanguageexpress.info/834.html)