前一张图片后一张图片切换显示实现实例页面

展示

回到相关文章 »

代码

CSS代码:
.box{width:512px; height:512px; margin-left:auto; margin-right:auto; background:url(/study/image/loading.gif) no-repeat center; text-align:center; overflow:hidden; position:relative;}
.box img{vertical-align:middle;}
.vline{display:inline-block; height:100%; width:0; vertical-align:middle;}
.prev, .next{width:50%; _height:2000px; background-image:url(about:blank); position:absolute; top:0; bottom:0; outline:none;}
.prev{cursor:url(pic_prev.cur), auto; left:0;}
.next{cursor:url(pic_next.cur), auto; right:0;}

.random{display:block; width:120px; height:36px; margin-left:auto; margin-right:auto;}
            
HTML代码:
<div id="box" class="box">                	
    <s class="prev" title="这是第一张图片"></s>
    <s class="next" title="下一张"></s>
    <img src="//image.zhangxinxu.com/image/study/s/s512/mm1.jpg" /><i class="vline"></i>
</div> 
<p><button class="random" id="randomSize">随机尺寸</button></p>  
            
JS代码:
var eleBox = document.getElementById("box"), eleImg = null, eleLink = null;
var indexImage = 0, indexLoop = 0
    // arrImgUrl实际应该是图片地址数组,这里的测试图片地址有规律,因此,直接数值代替
    , arrImgUrl = [1, 2, 3, 4, 5];
    
if (eleBox && 
    (eleImg = eleBox.getElementsByTagName("img")[0]) &&
    (eleLink = eleBox.getElementsByTagName("s")).length === 2)
{
    for (; indexLoop < 2; indexLoop += 1) {
        (function(index) {
            eleLink[index].onclick = function() {
                var indexWill = indexImage + (index? 1: -1);
                if (arrImgUrl[indexWill]) {
                    // 图片地址更换
                    eleImg.src = eleImg.src.replace(/mm\d/, "mm" + arrImgUrl[indexWill]);
                    indexImage = indexWill;
                }
                // 下面两对if语句是改变title值
                if (indexWill <= 0) {
                    eleLink[0].title = "这是第一张图片";
                } else {
                    eleLink[0].title = "上一张";
                }
                if (indexWill >= arrImgUrl.length - 1) {
                    eleLink[1].title = "这是最后一张图片";    
                } else {
                    eleLink[1].title = "下一张";
                }
                return false;
            };
            // 鼠标抬起,如果有右键动作,当前元素隐藏再显示,为contextmenu事件触发铺路
            eleLink[index].onmouseup = function(event) {
                event = event || window.event;
                var target = this;
                if (/^2|6|4|7$/.test(event.button)) {
                    target.style.visibility = "hidden";
                    setTimeout(function() { target.style.visibility = "visible";}, 16);            
                }        
            };        
        })(indexLoop);
    }
    
    // 随机尺寸,以展示自适应性
    var eleRandom = document.getElementById("randomSize");    
    eleRandom && (eleRandom.onclick = function() {
        eleBox.style.width = (512 + 256 * Math.random()) + "px";
        eleBox.style.height = (512 + 256 * Math.random()) + "px";
    });  
}