实现效果:鼠标经过左半部分,显示左按钮,点击显示上一张图;鼠标经过右半部分,显示右按钮,点击显示下一张图。
有淡入淡出效果。
js代码:
function picNext(id){
var picBox = document.getElementById(id),
picArray = picBox.getElementsByTagName('img'),
len = picArray.length,
boxWidth = picBox.offsetWidth;
picArray[0].style.display = 'block';
//创建左右按钮
var cssText1 = '41px; height:48px; top:50%; margin-top:-20px; cursor:pointer; left:10px; z-index:10',
cssText2 = '41px; height:48px; top:50%; margin-top:-20px; cursor:pointer; right:10px; z-index:10',
leftPic = new Image(),
rightPic = new Image();
leftPic.style.cssText = cssText1;
leftPic.src = 'images/btn_left.gif';
rightPic.style.cssText = cssText2;
rightPic.src = 'images/btn_right.gif';
picBox.appendChild(leftPic);
picBox.appendChild(rightPic);
//鼠标经过移出
function getEvent(event){
return event ? event : window.event;
}
picBox.onmousemove = function(e){
e = getEvent(e);
if(e.clientX + document.documentElement.scrollLeft - picBox.offsetLeft < boxWidth/2){
leftPic.style.display = 'block';
rightPic.style.display = 'none';
}
if(e.clientX + document.documentElement.scrollLeft - picBox.offsetLeft > boxWidth/2){
rightPic.style.display = 'block';
leftPic.style.display = 'none';
}
}
picBox.onmouseout = function(){
leftPic.style.display = 'none';
rightPic.style.display = 'none';
}
//点击事件
var now = 0;
function fadeIn(el){
el.style.opacity = 0;
el.style.filter = 'alpha(opacity = 0)';
el.style.display = 'block';
var n = 0;
function fadeShow(){
if (n < 1){
n += 0.1;
el.style.opacity = n;
el.style.filter = 'alpha(opacity = '+n*100+')';
var setTimeId = setTimeout(fadeShow, 50);
}else{
el.style.opacity = 1;
el.style.filter = 'alpha(opacity = 100)';
clearTimeout(setTimeId);
}
}
fadeShow();
}
function fadeOut(el){
el.style.opacity = 1;
el.style.filter = 'alpha(opacity = 100)';
var n = 1;
function fadeHide(){
if (n > 0){
n -= 0.1;
el.style.opacity = n;
el.style.filter = 'alpha(opacity = '+n*100+')';
var setTimeId = setTimeout(fadeHide, 50);
}else{
el.style.opacity = 0;
el.style.filter = 'alpha(opacity = 0)';
clearTimeout(setTimeId);
el.style.display = 'none';
}
}
fadeHide();
}
leftPic.onclick = function(){
if (now == 0){
alert('已经是第一张!')
}else{
fadeOut(picArray[now]);
fadeIn(picArray[now-1]);
now--;
}
}
rightPic.onclick = function(){
if (now == (len - 1)){
alert('已经最后一张!')
}else{
fadeOut(picArray[now]);
fadeIn(picArray[now+1]);
now++;
}
}
}
picNext('pic_box');
使用说明:picNext(id),只需传入图片的box的id即可,此box设置为相对定位,里边的图片设置绝对定位并隐藏。代码如下,
html代码:
<div id="pic_box">
<img src="images/pic1.jpg" alt="">
<img src="images/pic2.jpg" alt="">
<img src="images/pic3.jpg" alt="">
<img src="images/pic4.jpg" alt="">
<img src="images/pic5.jpg" alt="">
</div>
css代码:
body,div{ margin:0; padding:0;}
#pic_box{ position:relative; width:400px; height:300px; margin:50px auto 0;}
#pic_box img{ display:none; position:absolute;width:400px; height:300px; }