jQuery实现图片淡入淡出轮播及波浪运动效果
好久没写博客,想写的东西还是很多,真是计划赶不上变化唉。为期一个月的实习结束了,完成了官方网站的建设,虽然不是很难,但是也学到了很多东西。接下来的计划就是继续啃《JavaScript高级程序设计》,然后用bootstrap完成一个网站。 好了,言归正传。。。主要完成后的效果 点击在线预览 。
布局
由简入难,首先完成轮播图片以及两个按钮的布局。 这里给出两个按钮的css代码和html整体布局代码。 具体css按自己需求编写,关键点:
- 轮播图片要使用绝对定位相重叠,不然jquery淡入淡出效果会产生间隔。
- 两个小按钮是通过移动图片位置,产生黑点、白点效果。
<style type="text/css">
.switch .switch1{
display: block;
width: 10px;
height: 10px;
float: left;
cursor: pointer;
background: url(../img/switch.png) no-repeat -10px 0px;
}
.switch .switch2{
display: block;
width: 10px;
height: 10px;
float: left;
margin-left: 5px;
cursor: pointer;
background: url(../img/switch.png) no-repeat 0px 0px;
}
</style>
<div class="container">
<div class="switch">
<span class="switch1"></span><!--按钮位置左-->
<span class="switch2"></span><!--按钮位置右-->
</div>
<div class="banner_wrap1"></div><!--轮播图片1-->
<div class="banner_wrap2"></div><!--轮播图片2-->
</div>
实现图片自动淡入淡出的轮播效果
这里用到两个jquery方法,淡出效果fadeOut(),淡入效果fadeIn()以及js中setTimeout定时器的使用。代码如下
function switchone() {
$(".switch1").css({ "background-position": "0 0" });
$(".switch2").css({ "background-position": "-10px 0" });
$(".banner_wrap1").fadeOut(1000);
$(".banner_wrap2").fadeIn(1000);
bannerone();
}
function switchtwo() {
$(".switch2").css({ "background-position": "0 0" });
$(".switch1").css({ "background-position": "-10px 0" });
$(".banner_wrap2").fadeOut(1000);
$(".banner_wrap1").fadeIn(1000);
bannertwo();
}
var t1,t2;
function bannerone(){
clearTimeout(t1);
t2 = setTimeout(switchtwo, 5000);
}
function bannertwo(){
clearTimeout(t2);
t1 = setTimeout(switchone, 5000);
}
$(".switch1").click(function(){
switchtwo();
})
$(".switch2").click(function(){
switchone();
})
波浪运动效果
function waveone(){
$(".wave1").css({ "left": "-236px" }).animate({ "left": "-1233px" }, 25000,"linear", waveone);
}
function wavetwo(){
$(".wave2").css({ "left": "0" }).animate({ "left": "-1009px" }, 60000,"linear", wavetwo);
}
这是实现的jquery代码,再看看css代码如下
.wave1{
height: 85px;
width: 400%;
background: url(../img/wave1.png) repeat-x scroll;
position: absolute;
top:90%;
left: -236px;
}
.wave2{
height: 85px;
width: 400%;
background: url(../img/wave2.png) repeat-x scroll ;
position: absolute;
top:85%;
left:0;
}
这里用到jquery的自定义动画函数animate(params,[speed],[easing],[fn]),其中参数含义如下:
- params:一组包含作为动画属性和终值的样式属性和及其值的集合
- speed:三种预定速度之一的字符串(“slow”,”normal”, or “fast”)或表示动画时长的毫秒数值(如:1000)
- easing:要使用的擦除效果的名称(需要插件支持).默认jQuery提供”linear” 和 “swing”.
- fn:在动画完成时执行的函数,每个元素执行一次。
分析实现原理:
- 对图片进行绝对定位,将宽度设为远大于浏览器显示区域宽度,并沿x方向重复。
- 设置container的css:overflow: hidden;超出显示范围的图片部分隐藏。
- 最后通过jquery里的animate()方法反复移动图片的位置,实现波浪运动效果。
Comments