如果你想你的博客頁面某些部分引起讀者的注意,你可以使這些部分震動(dòng),如廣告,今天這篇文章將介紹怎樣使你的頁面中的元素震動(dòng)起來。
要達(dá)到這個(gè)目的我們需要使用到Jquery和Jquery UI。
首先讓我創(chuàng)建一個(gè)震動(dòng)塊,可以是圖片,也可以是普通的dom元素,如div、span等,把元素的id命名為shake,這里可以任意命名。
我們用圖片如下:
<img src="http://jqueryui.com/jquery-wp-content/themes/jquery/images/logo-jquery-ui.png" id="shake"/>
Jquery UI沒有現(xiàn)成的使元素震動(dòng)的方法,我們需要借助于effect方法來實(shí)現(xiàn),語法如下:
effect('shake', options, speed);
參數(shù)options(這里有三個(gè)參數(shù)):
•times:指定元素震動(dòng)次數(shù)
•distance:指定元素震動(dòng)幅度
•direction:指定元素震動(dòng)方向
下面是具體實(shí)現(xiàn)方法,設(shè)置震動(dòng)3次,每500ms調(diào)用一次震動(dòng):
function interval() {
$('#shake').effect('shake', { times:3 }, 100);
}
$(document).ready(function() {
var shake = setInterval(interval, 500);
});
<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>