Maison  >  Article  >  interface Web  >  Javascript natif réalise des compétences d'effet interactif pop-up d'image_javascript

Javascript natif réalise des compétences d'effet interactif pop-up d'image_javascript

WBOY
WBOYoriginal
2016-05-16 16:20:581278parcourir

【1】Utiliser var pour déclarer plusieurs variables est beaucoup plus rapide que d'utiliser var pour chaque variable

.

Copier le code Le code est le suivant :

var sScrollTop = document.body.scrollTop || document.documentElement.scrollTop,
sWindow_h = document.documentElement.clientHeight,
t_h = parseInt(this.getCss(this.getId('gy_photoBox_head'),'height')),
Hold_h = sWindow_h - t_h - 20,
largeur = this.nImgWidth ,
hauteur = this.nImgHeight

【2】Optimisation des événements Dom, lorsque window.onresize, définissez un timer, setTimeout, qui peut empêcher les appels fréquents d'événements

Copier le code Le code est le suivant :

windowResize:fonction(){
               var _that = this,
                 _timer = null;
// Limitation des fonctions
               window.onresize = function(){
                                                                                                          "                   _timer = setTimeout(function(){
Si( _that.tools.getId('gy_photoBox')){
                          _that.setBoxCss();
                 }
},100);

                                                                             >


[3] Fonction de traitement de chargement d'image


Copier le code Le code est le suivant :

/*
           @ src [String] L'adresse de l'image
​​​​​@success[Function] Fonction de rappel pour un chargement d'image réussi
​​​​​@ error [Fonction] Fonction de rappel en cas d'échec du chargement de l'image
*/
          imgLoading:function(opt){
            var _img = new Image(),
                 _that = this ;
​​​​​​​ _img.onload = fonction(){
                   _that.nImgWidth = this.width;
                   _that.nImgHeight = this.height;
Si(typeof opt.success == 'function'){
                                           setTimeout(function(){
                                          opt.success();
                      },300);
                }
            }
                _img.onerror = function(){
Si (type d'erreur opt.){
                        opt.error();
                                                                                                   }
                                                                                     // Remarque : il doit être placé sous l'événement onload, sinon un BUG apparaîtra dans ie
                _img.src = opt.src;
>

Code source :

Copier le code Le code est le suivant :

/*
auteur:laoguoyong
*/
(fonction(){
/* -------------------------Sélecteur simple------------------ --- -
@ Paramètre [chaîne]
​​---------------------------------------
★-Seules les options suivantes sont prises en charge-★
@ Prend en charge les sélecteurs de premier niveau : tels que '#id', '.class', 'p'
@ Prise en charge de la sélection descendante, telle que '.class p', 'body span'
@ Prend en charge la sélection de sous-éléments, tels que '.class>p', 'body>span'
​ ---------------------------------------------
@ return [Tableau]
*/
var sélecteur = fonction(str){
​​​​ //Définir un tableau d'éléments
var elem = [];
              /* Méthode privée
​​​​--------------*/
//Renvoie l'élément avec l'identifiant
         fonction _getId(id){
               return document.getElementById(id);
>
//Renvoie les éléments avec de tels noms - éléments
         fonction _getByClassName(className,parent){
            var class_array = [],
Node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
                 reg = new RegExp("(^|\s)" className "(\s|$)");
pour(var n=0,i=node.length;n Si(reg.test(node[n].className)){
                        class_array.push(node[n]);
                }
            }
                return class_array;
>
//Sélection de premier niveau, telle que '#id','p','.class'
              // renvoie [Array]
         fonction _getDom(s){
            var array_elem = [];
Si (s.indexOf('#')==0){
                   array_elem.push(_getId(s.slice(1)));
            }
                 else if(s.indexOf('.')==0){
                  array_elem = array_elem.concat(_getByClassName(s.slice(1)));
            }
            autre{
              var tag = document.getElementsByTagName(s);
pour(var n=0,i=tag.length;n                         array_elem.push(tag[n]);
                }
            }
               return array_elem;
>
          /*
​​​​​ @arry_elm [Array] : Tableau d'éléments, tel que ['.demo', 'p'], l'élément p sous .demo est sélectionné. Pour savoir s'il faut sélectionner des descendants ou des descendants, veuillez consulter le deuxième paramètre. explication
​​​​​@ r [String] - Facultatif (s'il n'est pas transmis, la valeur par défaut est de sélectionner les descendants) : '>', sélectionne les éléments descendants
        ------------------------------------
        @ return [Tableau]
        */
        fonction _query(array_elem,r){
            var noeud = array_elem,
                type_name = node[0].match(/#/)?'id_' node[0].slice(1):node[0].match(/./)?'className_' node[0].slice(1 ):'tagName_' noeud[0],
                enfant = _getDom(noeud[1]),
                type = type_name.split('_'),
                len = document.getElementsByTagName('*').length,
                reg = new RegExp("(^|\s)" type[1] "(\s|$)");;
            pour(var i=0,j=child.length;i                 var par = enfant[i].parentNode;
                pour(var n=0;n                     if(par.nodeType == 9){
                        pause;
                    >
                    if(reg.test(par[type[0]])){
                        elem.push(enfant[i]);
                        casser;                   
                    }autre{
                        if(r == '>') break;
                        par = par.parentNode;
                    }       
                >
            >
        >
        /* 接口
        -----------------------*/
        var elemStr = str.replace(/(^s )|(s $)/,'');
        if(document.querySelectorAll){
            var dom = document.querySelectorAll(elemStr);
            pour(var n=0,len=dom.length;n                 elem.push(dom[n]);
            >
        }autre{
            var    split = /[>s]/g.exec(elemStr);
            si (diviser) {
                var node = elemStr.split(split[0]);
                _query(node,split[0]);
            }autre{
                elem = elem.concat( _getDom(elemStr) );
            >
>
         renvoyer l'élément ;
>
/* Constructeur de fonction de fenêtre pop-up
​ -----------------------*/
Fonction LGY_photoBox(option){
This.opt = option;
This.oTarget = typeof option.target == 'object'?option.target:selector(option.target);
If(!this.oTarget) return;
This.nLen = this.oTarget.length; //Nombre total
This.aBigimg_src = []; //Grand tableau de données d'image
This.aTitle = []; //Tableau de données de titre
This.nIndex = 0; //Index
This.nImgWidth = 0; //Obtenir dynamiquement la largeur de l'image
This.nImgHeight = 0; //Obtenir dynamiquement la hauteur de l'image
This.nDelay = 0,2;
This.intit();
>
LGY_photoBox.prototype = {
         intit:function(){
               var _that = this;
This.getData();
pour(var n=0;n This.oTarget[n].index = n;
This.oTarget[n].onclick = function(e){
                       _that.createCover();
                var e = _that.tools.getEvent(e),
Cible = _that.tools.getTarget(e);
                                                                                                                                                                                      _that.tools.setCss(document.documentElement,{'height':'100%','overflow-y':'hidden','overflow-x':'hidden'});
// Récupère l'index actuel
                       _that.nIndex = this.index;
//Premier jugement
                      _that.firstLoad(_that.aBigimg_src[_that.nIndex], function(){
//Insérer une structure
                           _that.createBoxDom();
                                                                                                                                                             That.tools.getId('gy_photoBox_close').onclick = function(){
                     _that.removeBox();                                                                                                                                              } // Détermine si les boutons gauche et droit affichent
_that.btnIsShow();
// 上一张
_that.btnPrev();
// 下一张
_that.btnNext();
// 加载图片
_that.imgChange(_that.aBigimg_src[_that.nIndex]);
});
// 重置窗口大小
_that.windowResize();
// 键盘事件
_that.keyEvent();
//阻止跳转
return false;
}
}
},
createBoxDom:function(){
var doc = document,
exHtml = '',
boxHtml = doc.createElement('div');
boxHtml.id = 'gy_photoBox';
doc.body.appendChild(boxHtml);
if(typeof this.opt.appendHTML == 'string'){
exHtml = this.opt.appendHTML;
}
boxHtml.innerHTML = '
'+
                            '
'+
                            ''+
                            '
'+exHtml+'
'+
                            '
'+
                                'http://www.pconline.com.cn/blank.gif" />'+
                                ''+
                                '
'+
                                    ''+
                                        ''+
                                        '/'+this.nLen+
                                    '
'+
                                    '

'+
                                '
'+
                            '
';
        },
        createCover:fonction(){
            // 创建覆盖层
            var    doc = document,
                coverHtml = doc.createElement('div');
                coverHtml.id = 'gy_photoBox_cover';
            doc.body.appendChild(coverHtml);
            //设置覆盖层的样式
            this.tools.setCss(this.tools.getId('gy_photoBox_cover'),{'height':(doc.body.scrollTop || doc.documentElement.scrollTop) (doc.documentElement.clientHeight) 'px'});
        },
        setBoxCss:fonction(){
            var    doc = document,
                nScrollTop = doc.body.scrollTop || doc.documentElement.scrollTop,
                nWindow_h = doc.documentElement.clientHeight,
                eBox_head_h = this.tools.getId('gy_photoBox_head').clientHeight,
                eBox = this.tools.getId('gy_photoBox'),
                eBoxPadding = 10,
                hold_h = nWindow_h - eBoxPadding - 50 - eBox_head_h,
                largeur = this.nImgWidth ,
                hauteur = this.nImgHeight;
            // alert('nWindow_h :' nWindow_h '-' 'eBoxPadding :' eBoxPadding '-' 'eBox_head_h :' eBox_head_h);
            // 图片大小超过可见范围,进行缩放
            if(this.nImgHeight>hold_h){
                hauteur = hold_h,
                width = Math.ceil(this.nImgWidth*(height/this.nImgHeight));
            >
            //设置盒子在整个页面居中
            this.tools.setCss(eBox,{'width':width 'px',
                                    'hauteur':eBox_head_h hauteur 'px',
                                    'margin-left':-(width eBoxPadding)/2 'px',
                                    'top':nScrollTop (nWindow_h-height-eBoxPadding)/2 'px'});
            this.tools.setCss(this.tools.getId('gy_photoBox_main'),{'width':largeur 'px','height':hauteur 'px'});
            //设置覆盖层的样式
            this.tools.setCss(this.tools.getId('gy_photoBox_cover'),{'height':nScrollTop doc.documentElement.clientHeight 'px'});
        },
        removeBox:fonction(){
            var doc = document;
            if(this.tools.getId('gy_photoBox')){
                doc.body.removeChild(this.tools.getId('gy_photoBox'));
            >
            if(this.tools.getId('gy_photoBox_cover')){
                document.body.removeChild(this.tools.getId('gy_photoBox_cover'));
            >
            this.tools.setCss(document.documentElement,{'height':'auto','overflow-y':'auto','_overflow-y':'scroll','overflow-x':'auto'}) ;
        },
        getData:fonction(){
            pour(var n=0;n                 var src = this.oTarget[n].getAttribute('href'),
                    title = this.oTarget[n].getAttribute('title');
                this.aBigimg_src.push(src);
                if(!title) titre = '';
                this.aTitle.push(titre);
            >
        },
        btnIsShow:function(){
            this.tools.setCss(this.tools.getId('gy_photoBox_prev'),{'display':'block'});
            this.tools.setCss(this.tools.getId('gy_photoBox_next'),{'display':'block'});
            if(this.nIndex == 0) this.tools.setCss(this.tools.getId('gy_photoBox_prev'),{'display':'none'});
            if(this.nIndex == (this.nLen-1)) this.tools.setCss(this.tools.getId('gy_photoBox_next'),{'display':'none'});
        },
        imgChange:fonction(){
            var _that = ceci,
                _src = this.aBigimg_src[this.nIndex],
                eLoadingTips = this.tools.getId('gy_photoBox_img_loading'),
                eImg = this.tools.getId('gy_photoBox_img'),
                eTitle = this.tools.getId('gy_photoBox_title'),
                eInfor = this.tools.getId('gy_photoBox_infor');
            // 显示loading图片
            this.tools.setCss(eLoadingTips,{'display':'block'});
            this.tools.setCss(eInfor,{'display':'none'});
            // 判断左右按钮显示
            this.btnIsShow();
            // 图片加载处理
            this.imgLoading({
                'src':_src,
                'succès':function(){
                    _that.tools.setCss(eLoadingTips,{'display':'none'});
                    _that.tools.setCss(eInfor,{'display':'block'});
                    // 设置真实图片路径,标题,当前页码
                       eImg.src = _src;
eTitle.innerHTML = _that.aTitle[_that.nIndex];
                       _that.tools.getId('gy_photoBox_index').innerHTML = (_that.nIndex 1);
                                                                                                                                                                                                          _that.setBoxCss();
// Une fenêtre pop-up apparaît
                   _that.tools.setCss(_that.tools.getId('gy_photoBox'),{'visibility':'visible'});
Si(_that.tools.getId('gy_photoBox_firstLoad')){
document.body.removeChild(_that.tools.getId('gy_photoBox_firstLoad'));
                 }
// Fonction de rappel exécutée à chaque commutation
Si(typeof _that.opt.onChange == 'function'){
                     _that.opt.onChange({'src':_src,'index':_that.nIndex,'title':_that.aTitle[_that.nIndex]});
                                                                                                                                                                                              },
                 'erreur':function(){
                                           setTimeout(function(){
                        _that.tools.setCss(eLoadingTips,{'display':'none'});
                     },200);
                      eImg.src = 'gyPhotoBox/error.png';
eTitle.innerHTML = 'Aucune image associée';
                        _that.nImgWidth = 400;
                        _that.nImgHeight = 300;
                       _that.setBoxCss();
                   _that.tools.setCss(_that.tools.getId('gy_photoBox'),{'visibility':'visible'});
Si(_that.tools.getId('gy_photoBox_firstLoad')){
document.body.removeChild(_that.tools.getId('gy_photoBox_firstLoad'));
                 }
                }
            });
},
          btnPrev:function(){
               var _that = this;
This.tools.getId('gy_photoBox_prev').onclick = function(){
                _that.nIndex--;
                _that.imgChange();
            >
        },
        btnSuivant:fonction(){
            var _that = ceci;
            this.tools.getId('gy_photoBox_next').onclick = function(){
                _that.nIndex ;
                _that.imgChange();
            >
        },
        keyEvent:fonction(){
            var _that = ceci;
            document.onkeydown = fonction(e){
                var e = e || window.event;
                commutateur(e.keyCode){
                    cas 37 :{
                        if(_that.nIndex != 0&&_that.tools.getId('gy_photoBox_prev')){
                            _that.nIndex--;
                            _that.imgChange();   
                        }   
                    };pause;
                    cas 39 :{
                        if(_that.nIndex != (_that.nLen-1)&&_that.tools.getId('gy_photoBox_next')){
                            _that.nIndex ;
                            _that.imgChange();   
                        }           
                    };pause;
                    cas 27 :{
                        _that.removeBox();                           
                    };pause;
                >
            >
        },
        /*
        @ src [String] 图片的地址
        @ success [Fonction] 图片加载成功的回调函数
        @ erreur [Fonction] 图片加载失败的回调函数
        */
        imgChargement :fonction(opt){
            var _img = nouvelle Image(),
                _ça = ceci ;
            _img.onload = fonction(){
                _that.nImgWidth = this.width;
                _that.nImgHeight = this.height;
                if(typeof opt.success == 'function'){
                    setTimeout(function(){
                        opt.success();
                    },300);
                >
            >
            _img.onerror = fonction(){
                si (type d'erreur opt.) {
                    opt.error();
                }           
            >
            // 注意:要放在onload事件下面,否则ie会出现BUG
            _img.src = opt.src;
        },
        firstLoad:fonction(src,callback){
            var _that = ceci,
                html = document.createElement('div');
                html.id = 'gy_photoBox_firstLoad';
            document.body.appendChild(html);
            this.tools.setCss(this.tools.getId('gy_photoBox_firstLoad'),{'top':(document.body.scrollTop || document.documentElement.scrollTop) (document.documentElement.clientHeight/2) 'px'}) ;
            if(typeof callback == 'function') {
                rappel();
            >
        },
        windowResize:fonction(){
            var _that = ceci,
                _timer = nul;
            // 函数节流
            window.onresize = fonction(){
                clearTimeout(_timer);
                _timer = setTimeout(function(){
                    if( _that.tools.getId('gy_photoBox')){
                        _that.setBoxCss();
                    >
                },100);
            }       
        },
        outils:fonction(){
            revenir{
                getEvent:fonction(e){
                    retourner e || window.event;
                },
                getTarget:fonction(e){
                    retourner e.target || e.srcElement;
                },
                prévenirDefault:fonction(e){
                    e.preventDefault?e.preventDefault():e.returnValue = false;
                },
                getId:fonction(id){
                    return document.getElementById(id);
                },
                getCss:fonction (nœud, valeur){
                    return node.currentStyle?node.currentStyle[value]:getComputedStyle(node,null)[value];
                },
                setCss:fonction(noeud,val){
                    pour(var v dans val){
                        node.style.cssText = ';' v':'val[v];
                    >
                >
            >
        }()
    >
    window.LGY_photoBox = LGY_photoBox;
})();

最终效果图:

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn