首頁 >web前端 >js教程 >基於zepto.js實作仿手機QQ空間的大圖檢視元件ImageView.js詳解_javascript技巧

基於zepto.js實作仿手機QQ空間的大圖檢視元件ImageView.js詳解_javascript技巧

WBOY
WBOY原創
2016-05-16 16:11:131549瀏覽

呼叫方式 :ImageView(index,imgData)  --index參數 為圖片預設顯示的索引值,類型 為Number  --imaData參數 為圖片url陣列 ,類型為Array

使用之前要先引入 zepto.js 檔案

ImageView.js具體程式碼如下:

複製程式碼 程式碼如下:

/*
 * ImageView v1.0.0
 * --基於zepto.js的大圖檢視
 * --呼叫方法 ImageView(index,imgDada)
 * --index 圖片預設值顯示索引,Number  --imgData 圖片url陣列,Array
 * */
var ImageView=(function(window,$){
    var _this=$("#slideView"),_ImgData=[],_index=0,_length=0,
        _start=[],_org=[],_orgTime=null,
        _lastTapDate=null,
        _zoom=1,_zoomXY=[0,0],_transX=null,
        _advancedSupport = false,
        _doubleDistOrg=1,_doubleZoomOrg=1,isDoubleZoom = false,
        isSlide=true,isDrag=false,timer=null,
        winW=window.innerWidth,winH=window.innerHeight;
    /**
     * 事件物件 event
    */
    var Event={
        touchstart:function(e){
            e.preventDefault();
            if (_advancedSupport && e.touches && e.touches.length >= 2) {
                var img = getImg();
                $(img).css({"-webkit-transitionDuration": "0ms","transitionDuration": "0ms"});
                _doubleZoomOrg = _zoom;
                _doubleDistOrg = getDist(e.touches[0].pageX, e.touches[0].pageY, e.touches[1].pageX, e.touches[1].pageY                 isDoubleZoom = true;
                return
            }
            e = e.touches ? e.touches[0] : e;
            isDoubleZoom = false;
            _start = [e.pageX, e.pageY];
            _org = [e.pageX, e.pageY];
            _orgTime = Date.now();
            _transX = -_index * winW;
            if(_zoom!=1){
                _zoomXY = _zoomXY || [0, 0];
                _orgZoomXY = [_zoomXY[0], _zoomXY[1]];
                var img = getImg();
                img&&($(img).css({"-webkit-transitionDuration": "0ms","transitionDuration": "0ms"}));
                isDrag = true
            }else{
                _this.find(".pv-inner").css({"-webkit-transitionDuration":"0ms","transitionDuration":"0ms"});
;
;             }
        },
        touchmove:function(e){
            e.preventDefault();
            if (_advancedSupport && e.touches && e.touches.length >= 2) {
                var newDist = getDist(e.touches[0].pageX, e.touches[0].pageY, e.touches[1].pageX, e.touches[                var img = getImg();
                $(img).css({"-webkit-transitionDuration": "0ms","transitionDuration": "0ms"});
                if (_zoom                     _zoom = 1;
                    _zoomXY = [0, 0];
                    $(img).css({"-webkit-transitionDuration": "200ms","transitionDuration": "200ms"})
                } else if (_zoom > getScale(img) * 2){
                     _zoom = getScale(img) * 2;
                }
                $(img).css({"-webkit-transform": "scale(" _zoom ") 翻譯(" _zoomXY[0] "px," _zoomXY[1] "px)","transform": "scale(" _zoom ") 翻譯(" _zoomXY[0] "px," _zoomXY[1] "px)"});
                返回
            }
            if (isDoubleZoom){
                返回;
            }
            e = e.touches ? e.touches[0] : e;
            if (_zoom != 1) {
                var deltaX = (e.pageX - _start[0]) / _zoom;
                var deltaY = (e.pageY - _start[1]) / _zoom;
                _start = [e.pageX, e.pageY];
                var img = getImg();
                var newWidth = img.clientWidth *_zoom,
                    newHeight = img.clientHeight * _zoom;
                var borderX = (newWidth - winW) / 2 / _zoom,
                    borderY = (newHeight - winH) / 2 / _zoom;
                (borderX >= 0)&&(_zoomXY[0] borderX)&&(deltaX /= 3);
                (borderY > 0)&&(_zoomXY[1] borderY)&&(deltaY /= 3);
                _zoomXY[0] = deltaX;
                _zoomXY[1] = deltaY;
                (_length == 1 && newWidth                 (_length == 1 && newHeight                 $(img).css({"-webkit-transform": "scale(" _zoom ") 翻譯(" _zoomXY[0]
                    "px," _zoomXY[1] "px)","transform": "scale(" _zoom ") 翻譯(" _zoomXY[0]
                    "px," _zoomXY[1] "px)"})
            }其他{
                if (!isSlide) return;
                var deltaX = e.pageX - _start[0];
                (_transX > 0 || _transX                 _transX = -_index * winW deltaX;
                _this.find(".pv-inner").css({"-webkit-transform":"translate(" _transX "px,0px) translateZ(0)"});
            }
        },
        touchend:函數(e){
            if (isDoubleZoom) {
                返回;
            }
            if (_zoom != 1) {
                if (!isDrag){return;}
                var img = getImg();
                var newWidth = img.clientWidth *_zoom,
                    newHeight = img.clientHeight * _zoom;
                var borderX = (newWidth - winW) / 2 / _zoom,
                    borderY = (newHeight - winH) / 2 / _zoom;
                if (_length > 1 && borderX >= 0) {
                    var updateDelta = 0;
                    var switchDelta = winW / 6;
                    if (_zoomXY[0]                         updateDelta = 1;
                    }else if (_zoomXY[0] > borderX switchDelta / _zoom && _index > 0){
                        updateDelta = -1;
                    }
                    if (updateDelta != 0) {
                        縮小(img);
                        changeIndex(_index updateDelta);
                        返回
                    }
                }
                var delta = Date.now() - _orgTime;
                if (delta                     (delta                     var deltaDis = Math.pow(180 / delta, 2);
                    _zoomXY[0] = (_zoomXY[0] - _orgZoomXY[0]) * deltaDis;
                    _zoomXY[1] = (_zoomXY[1] - _orgZoomXY[1]) * deltaDis;
$(img).css({"-webkit-transition": "400ms 三次貝塞爾曲線(0.08,0.65,0.79,1)","transition": "400ms 三次貝塞爾曲線(0.08,0.65,0.79 ,1)" })
                } 其他{
                                $(img).css({"-webkit-transition": "200ms 線性","transition": "200ms 線性"});
;
;
;
;
;
;
;
;                 }
                if (borderX >= 0){
                    if (_zoomXY[0]                        _zoomXY[0] = -borderX;
                    }否則 if (_zoomXY[0] > borderX){
                       _zoomXY[0] = borderX;
                    }
                }
                if (borderY > 0){
                    if (_zoomXY[1]                        _zoomXY[1] = -borderY;
                    }否則 if (_zoomXY[1] > borderY){
                       _zoomXY[1] = borderY;
                    }
                }
                if (Math.abs(_zoomXY[0]) $(img).css({"-webkit-transform": "scale(" _zoom ") 翻譯(0px," _zoomXY[1] "px)","transform": "scale(" _zoom ") 翻譯(0px ," _zoomXY[1] "px)"});
                   且返回
                } 其他{
$(img).css({"-webkit-transform": "scale(" _zoom ") 翻譯(" _zoomXY[0] "px," _zoomXY[1] "px)","transform": "scale(" _zoom ") 翻譯(" _zoomXY[0] "px," _zoomXY[1] "px)"});
                }
                isDrag = false             }其他{                 if (!isSlide){ return;}                 var deltaX = _transX - -_index * winW;                 var updateDelta = 0;                 若 (deltaX > 50){                     updateDelta = -1;                }否則為 if(deltaX                     updateDelta = 1;
                }
                _index=_index updateDelta;
                變更索引(_index);
                isSlide =false
            }
        },
        點選:函數(e){
            _zoom=1;
            _zoomXY=[0,0];
            _this.css("不透明度","0");
            計時器=setTimeout(function(){
                _this.css({"display":""}).html("");
                解除綁定();
            },150)
        },
        dobelTap:函數(e){
            清除逾時(計時器);
            var now = 新日期;
            if (現在 - _lastTapDate                 返回;
            }
            _lastTapDate = 現在;
            var img = getImg();
            若 (!img){
                返回;
            }
            if (_zoom != 1){
                縮減(img);
            }其他{
                放大(img);
            }
        },
        setView:function(e){
            winW=window.innerWidth;
            winH=window.innerHeight;
            _this.width(window.innerWidth).height(window.innerHeight);
            翻譯((-_index*window.innerWidth),0,0,$(".pv-inner")[0]);
            縮小(getImg())
        }
    };
    var handleEvent=function(e){
        開關(e.type){
            案例「touchstart」:
                Event.touchstart(e);
                休息;
            案例「touchmove」:
                Event.touchmove(e);
                休息;
            案例「touchcancel」:
            個案「touchend」:
                Event.touchend(e);
                休息;
            個案「方向改變」:
            個案「調整大小」:
                Event.setView(e);
                休息
        }
    };
    /**
     * 綁定事件
    */
    var bind=function(){
        _this.on("singleTap",function(e){
            e.preventDefault();
            var now = 新日期;
            if (現在 - _lastTapDate                 返回;           
            }
            _lastTapDate = 現在;
            Event.click(e);
            回復錯誤;
        }).on("doubleTap", function(e) {
            e.preventDefault();
            Event.dobelTap(e);
            回復錯誤;
        });
        _this.on("touchstart touchmove touchend touchcancel", function(e) {
            處理事件(e);
        });
        Event.setView();
        視窗中的「onorientationchange」? window.addEventListener("orientationchange",Event.setView,false) : window.addEventListener("resize",Event.setView,false);
    };
    /**
     * 解除事件
    */
    var unbind= function() {
         _this.off();
        視窗中的「onorientationchange」? window.removeEventListener("orientationchange",Event.setView, false) : window.removeEventListener("resize",Event.setView, false)
    };
    var getDist= function(x1, y1, x2, y2) {
        return Math.sqrt(Math.pow(x2 - x1, 2) Math.pow(y2 - y1, 2), 2)
    }
    /**
     * 圖片縮放
    */
    var getScale=function(img) {
        var h = img.naturalHeight, w = img.naturalWidth,
        比例=w*h/(img.clientHeight*img.clientWidth);
        回報比例;
    };
    var scaleUp=函數(img) {
        var scale = getScale(img);
        若(規模> 1)
$(img).css({"-webkit-transform": "scale("scale")","transform": "scale("scale")","-webkit-transition": "200ms","transition ": "200ms"});
        _zoom = 比例;
    };
    var scaleDown=函數(img) {
        _zoom = 1;
        _zoomXY = [0, 0];
        _doubleDistOrg = 1;
        _doubleZoomOrg = 1;
$(img).css({"-webkit-transform": "scale(1)","transform": "scale(1)","-webkit-transition": "200ms","transition": "200ms “});
    };
    /**
     * 滑動效果
     * dist
    */
    var 翻譯 = 函數( distX,distY,speed,ele) {
        if( !!ele ){ ele=ele.style; }else{ return; }
        ele.webkitTransitionDuration =  ele.MozTransitionDuration = ele.msTransitionDuration = ele.OTransitionDuration = ele.transitionDuration =  speed + 'ms';
        ele.webkitTransform = 'translate(' + distX + 'px,'+distY+'px)' + 'translateZ(0)';
        ele.msTransform = ele.MozTransform = ele.OTransform = 'translateX(' + distX + 'px) translateY(' + distY + 'px)';
    };
    /**
     * 更改索引值 _index
     */
    var changeIndex=function(index,force){
        if (index < 0){
index = 0;
}else if(index >= _length){
            index =_length - 1;
        }
        _index = index;
        translate((-_index*window.innerWidth),0,force? "0" : "200" ,$(".pv-inner")[0]);
        $("#J_index").html(_index+1+"/"+_length);
        imgLoad();
    }
    /**
     * 图片获取
     */
    var getImg=function(index) {
        var img = _this.find("li").eq(index || _index).find("img");
        if (img.size() == 1){
            return img[0];
        }else{
            return null
        }
    }
    /**
     * 图片加载
     */
    var imgLoad=function(){
        if($(".pv-img").eq(_index).find("img")[0]){
            $("#J_loading").css("display","");
            return;
        }else{
            $("#J_loading").css("display","block");
            var tempImg=new Image(),w,h,set;
            tempImg.src=_ImgData[_index];
            $(".pv-img").eq(_index)[0].appendChild(tempImg);
            tempImg.onload=function(){
                $("#J_loading").css("display","");
            }
        }
    };
    /**
     * 创建大图查看Dome结构
     */
    var Create=function(){
        _this.append("
    ").append("

    "+(_index+1)+"/"+_length+"

    ").append("")
            for(var i=0;i<_length;i++){
    $(".pv-inner").append("
  • ")
            }
            imgLoad();
        };
        /**
         * 大图查看初始化
         */
        var init=function(){
            !!_this[0]||$("body").append("
    ");
            _this=$("#slideView");
            ($.os.iphone || $.os.android && parseFloat($.os.version) >= 4)&&(_advancedSupport = true);
        }();
        /**
         * 大圖檢視回傳介面函數
         * ImageView(index,data)
         * index 初始指標值 nubmer
         * data 圖片陣列 array
        */
        var ImageView=function(index,data){
            _ImgData=data;
            _index=index;
            _length=data.length;
            //建立dom結構
            Create();
            //dom結構顯示
            _this.css("display","block");
            //綁定事件
            bind();
        }
        return ImageView;
    })(window,Zepto);
      

    ImageView.js用到的css程式碼如下:

    複製程式碼 程式碼如下:

    /*大圖查看*/
    .slide-view {背景:#000;位置:固定;寬度:100%;高度:100%;溢出:隱藏;頂部:0;左:0;z-index:100;不透明度:0;顯示:無; -webkit-animation:fadeIn .2s 線性前進;animation:fadeIn .2s 線性前進;-webkit-touch-callout: none;-webkit-transform-style:preserve-3d; }
    .slide-view .counts {位置:絕對;頂部:5%;左:0;右:0;文字對齊:中心;字體大小:0;-webkit-transform-style:保留-3d; }
    .slide-view .counts .value {邊框半徑:9px;行高:18px;填滿:0 6px;字體大小:11px;顯示:內聯塊;背景顏色:rgba(102,102,102,.6);顏色:#f1f1f1 ;}
    .pv-inner {位置:相對;z-index:-1;顯示:-webkit-box;顯示:box;寬度:100%;高度:100%;-webkit-transition:全部350ms線性;-webkit-backface -可見性:隱藏;過渡:全部350 毫秒線性;背面可見性:隱藏;-webkit-touch-callout:無;-webkit-transform-style:保留3d; }
    .pv-inner li {文字對齊:中心;顯示:-webkit-box;顯示:框;-webkit-box-align:中心;溢出:隱藏;寬度:100%;高度:100%;-webkit-touch - callout:無;背面可見性:隱藏;-webkit-transform-style:preserve-3d; }
    .pv-inner img {最大寬度:97%;最大高度:100%;-webkit-transform:scale(1)translate(0px,0px);transform:scale(1)translate(0px,0px);可見性:可見;-webkit-transition: 200ms;transition: 200ms;-webkit-user-select: none;user-select: none;display: block;margin: 0 auto;backface-visibility: hide;-webkit-transform-style :保留-3d; }
    @-webkit-keyframes fadeIn{
        0%{不透明度:0;}
        100%{不透明度:1;}
    }
    @關鍵影格淡入{
        0%{不透明度:0;}
        100%{不透明度:100%;}
    }
    /*--------------------正在加載------------------------*/
    .ui-loading {位置:絕對;左:50%;上:50%;顯示:無;垂直對齊:中間;字體:0/0 arial;邊距:-5px 0 0 -10px;}
    .ui-loading i {顯示:內聯塊;寬度:5px;高度:12px;背景:#fff;垂直對齊:頂部;-webkit-animation:加載旋轉1秒無限線性;動畫:加載旋轉1秒無限線性;}
    .ui-loading i {-webkit-animation:loading-spin 1s無限線性;animation:loading-spin 1s無限線性}
    .ui-loading i.t2 {邊距:0 3px;-webkit-animation-name:loading-spin-one;animation-name:loading-spin-one}
    .ui-loading i.t3 {-webkit-animation-name:loading-spin-two;animation-name:loading-spin-two}
    @-webkit-keyframes 載入旋轉 {
        0% {不透明度: 0}
        30% {不透明度: 1;-webkit-transform: scale(1,1.2)}
        60% {不透明度: 0;-webkit-transform: 比例(1)}
        100% {不透明度: 0}
    }
    @-webkit-keyframes 載入旋轉一 {
        0% {不透明度: 0}
        20% {不透明度: 0}
        50% {不透明度: 1;-webkit-transform: scale(1,1.2)}
        80% {不透明度: 0;-webkit-transform: 比例(1)}
        100% {不透明度: 0}
    }
    @-webkit-keyframes 載入旋轉兩個 {
        0% {不透明度: 0}
        40% {不透明度: 0}
        70% {不透明度: 1;-webkit-transform: scale(1,1.2)}
        100% {不透明度: 0;-webkit-transform: 比例(1)}
    }
    @keyframes 加載旋轉 {
        0% {不透明度: 0}
        30% {不透明度: 1;變換: 比例(1,1.2)}
        60% {不透明度: 0;變換: 比例(1)}
        100% {不透明度: 0}
    }
    @keyframes 載入旋轉一 {
        0% {不透明度: 0}
        20% {不透明度: 0}
        50% {不透明度: 1;變換: 比例(1,1.2)}
        80% {不透明度: 0;變換: 比例(1)}
        100% {不透明度: 0}
    }
    @keyframes 加載旋轉兩個 {
        0% {不透明度: 0}
        40% {不透明度: 0}
        70% {不透明度: 1;變換: 比例(1,1.2)}
        100% {不透明度: 0;變換: 比例(1)}
    }
    /*--------------------載入結束----------------------*/

    ps:程式碼功能比較簡單,可能會有初始化問題。但也能勉強使用

    下用的是使用ImageView.js的一個例子:

    複製程式碼程式碼如下:



       
           
           
           
       
       
           
           
            <script><br />             ;(function(){<br />                 //取得 html 的圖片元素<br />                 var aImg=document.querySelectorAll("img"),<br />                     aImgSrc=[];<br />                 //為圖片綁定點選事件<br />                 for(var i=0,l=aImg.length;i<l;i ){<br />                     aImg[i].index=i;<br />                     aImg[i].className =" conPic";<br />                     aImgSrc.push(aImg[i].src);<br />                 }<br />                 for(var i=0;i<$(".conPic").length;i ){<br />                     if($(".conPic")[i].complete){<br />                         addTap($(".conPic")[i])<br />                     }else{<br />                         $(".conPic")[i].onload=function(){<br />                             addTap(this);<br />                         }<br />                     }<br />                 }<br />                 為 addTap(obj){<br />                     $(obj).on("tap",function(){<br />                         //則以ImageView<br />                         ImageView($(obj)[0].index,aImgSrc);<br />                     })<br />                 }<br />             })();<br />         </script>
       

    以上就是本文的全部內容了,希望大家能夠喜歡

    陳述:
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn