Rumah  >  Artikel  >  hujung hadapan web  >  Javascript asli merealisasikan kemahiran effect_javascript interaktif pop timbul gambar

Javascript asli merealisasikan kemahiran effect_javascript interaktif pop timbul gambar

WBOY
WBOYasal
2016-05-16 16:20:581317semak imbas

【1】Menggunakan var untuk mengisytiharkan berbilang pembolehubah adalah lebih pantas daripada menggunakan var untuk setiap pembolehubah

Salin kod Kod adalah seperti berikut:

var sScrollTop = document.body.scrollTop ||.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,
lebar = ini.nImgWidth ,
tinggi = ini.nImgHeight;
【2】Pengoptimuman acara Dom, apabila window.onresize, tentukan pemasa, setTimeout, yang boleh menghalang panggilan acara yang kerap

Salin kod Kod adalah seperti berikut:
windowResize:function(){
               var _itu = ini,
                 _pemasa = batal;
// Pendikitan fungsi
               window.onresize = function(){
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  “                  _pemasa = setTimeout(fungsi(){
Jika( _that.tools.getId('gy_photoBox')){
                          _that.setBoxCss();
                 }

},100);                                                                                                                     }




[3] Fungsi pemprosesan pemuatan imej


Salin kod Kod adalah seperti berikut:

/*
           @ src [String] Alamat imej
            @ kejayaan [Fungsi] Fungsi panggil balik untuk pemuatan imej yang berjaya
​​​​​@ error [Fungsi] Fungsi panggil balik untuk kegagalan pemuatan imej
*/
          imgLoading:function(opt){
            var _img = Imej baharu(),
                 _itu = ini;
​​​​​​​ _img.onload = function(){
                   _that.nImgWidth = this.width;
                   _that.nImgHeight = this.height;
If(typeof opt.success == 'function'){
                                           setTimeout(function(){
                                          opt.success();
                      },300);
                }
            }
                _img.onerror = function(){
If(typeof opt.error){
                        opt.error();
                                                                                                           }
// Nota: Ia mesti diletakkan di bawah acara Onload, jika tidak, bug akan muncul dalam IE
                _img.src = opt.src;
}

Kod sumber:

Salin kod Kod adalah seperti berikut:

/*
pengarang:laoguoyong
*/
(fungsi(){
/* -------------------------Pemilih mudah------------------ --- -
@ parameter [rentetan]
---------------------------------------
★-Hanya sokong pilihan berikut-★
@ Menyokong pemilih peringkat pertama: seperti '#id', '.class', 'p'
@ Sokong pemilihan keturunan, seperti '.class p', 'span badan'
@ Menyokong pemilihan sub-elemen, seperti '.class>p', 'body>span'
​ ---------------------------------------
@ pulangkan [Array]
*/
var selector = function(str){
​​​​ //Tentukan tatasusunan elemen
var elem = [];
              /* Kaedah peribadi
​​​​​​​​​​​*/
//Kembalikan elemen dengan id
         fungsi _getId(id){
               pulangkan document.getElementById(id);
}
//Kembalikan elemen dengan nama sedemikian - elemen
Fungsi _getByClassName(className,parent){
            var class_array = [],
Nod = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
                 reg = new RegExp("(^|\s)" className "(\s|$)");
for(var n=0,i=node.length;n If(reg.test(nod[n].className)){
                        class_array.push(nod[n]);
                }
            }
                kembali class_array;
}
//Pemilihan peringkat pertama, seperti '#id','p','.class'
              // kembalikan [Array]
         fungsi _getDom(s){
            var array_elem = [];
Jika (s.indexOf('#')==0){
                   array_elem.push(_getId(s.slice(1)));
            }
                 lain jika(s.indexOf('.')==0){
                  array_elem = array_elem.concat(_getByClassName(s.slice(1)));
            }
            lain{
              var tag = document.getElementsByTagName(s);
for(var n=0,i=tag.length;n                         array_elem.push(tag[n]);
                }
            }
               kembalikan array_elem;
}
         /*
​​​​​ @arry_elm [Array]: Tatasusunan elemen, seperti ['.demo','p'], elemen p di bawah .demo dipilih Sama ada untuk memilih keturunan atau keturunan, sila lihat parameter kedua penjelasan
​​​​​@ r [String] - Pilihan (jika tidak diluluskan, lalai adalah untuk memilih keturunan): '>', memilih elemen keturunan
        -------------------------
        @ pulangkan [Array]
        */
        fungsi _query(array_elem,r){
            nod var = array_elem,
                type_name = nod[0].match(/#/)?'id_' nod[0].slice(1):node[0].match(/./)?'className_' nod[0].slice(1 ):'tagName_' nod[0],
                anak = _getDom(nod[1]),
                type = type_name.split('_'),
                len = document.getElementsByTagName('*').panjang,
                reg = new RegExp("(^|\s)" type[1] "(\s|$)");;
            for(var i=0,j=child.length;i                 var par = child[i].parentNode;
                untuk(var n=0;n                     if(par.nodeType == 9){
                        rehat;
                    }
                    if(reg.test(par[type[0]])){
                        elem.push(kanak-kanak[i]);
                        pecah;                   
                    }lain{
                        if(r == '>') putus;
                        par = par.parentNode;
                    }       
                }
            }
        }
        /* 接口
        -----------------------*/
        var elemStr = str.replace(/(^s )|(s $)/,'');
        if(document.querySelectorAll){
            var dom = document.querySelectorAll(elemStr);
            untuk(var n=0,len=dom.length;n                 elem.push(dom[n]);
            }
        }lain{
            var    split = /[>s]/g.exec(elemStr);
            jika(berpisah){
                var nod = elemStr.split(split[0]);
                _query(nod,split[0]);
            }lain{
                elem = elem.concat( _getDom(elemStr) );
            }
}
         elem kembali;
}
/* Pembina fungsi tetingkap timbul
​ -----------------------*/
Fungsi LGY_photoBox(pilihan){
This.opt = pilihan;
This.oTarget = typeof option.target == 'objek'?option.target:selector(option.target);
Jika(!this.oTarget) kembali;
This.nLen = this.oTarget.length; //Jumlah nombor
This.aBigimg_src = []; //Susun atur data imej besar
This.aTitle = []; //Title data array
This.nIndex = 0; //Indeks
This.nImgWidth = 0; //Dapatkan lebar imej
secara dinamik This.nImgHeight = 0; //Dapatkan ketinggian gambar secara dinamik
This.nDelay = 0.2;
This.intit();
}
LGY_photoBox.prototype = {
         intit:function(){
               var _itu = ini;
This.getData();
untuk(var n=0;n This.oTarget[n].index = n;
This.oTarget[n].onclick = function(e){
                       _that.createCover();
                var e = _that.tools.getEvent(e),
Sasaran = _that.tools.getTarget(e);
// Tetapkan halaman semak imbas tanpa jalur bergolek
                   _that.tools.setCss(document.documentElement,{'height':'100%','overflow-y':'hidden','overflow-x':'hidden'});
                                                                                  // Dapatkan indeks semasa
                        _that.nIndex = this.index;
//Penghakiman pertama
                      _that.firstLoad(_that.aBigimg_src[_that.nIndex], function(){
//Sisipkan struktur
                          _that.createBoxDom();
                                                                                                                                                                                                                                                                                                                                                      That.tools.getId('gy_photoBox_close').onclick = function(){
                     _that.removeBox();                                                                                                                                                                                         // Tentukan sama ada butang kiri dan kanan memaparkan
_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:function(){
            // 创建覆盖层
            var    doc = dokumen,
                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:function(){
            var    doc = dokumen,
                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,
                lebar = ini.nImgWidth ,
                ketinggian = ini.nImgHeight;
            // alert('nWindow_h:' nWindow_h '-' 'eBoxPadding:' eBoxPadding '-' 'eBox_head_h:' eBox_head_h);
            // 图片大小超过可见范围,进行缩放
            if(this.nImgHeight>hold_h){
                ketinggian = hold_h,
                lebar = Math.ceil(this.nImgWidth*(height/this.nImgHeight));
            }
            //设置盒子在整个页面居中
            this.tools.setCss(eBox,{'width':width 'px',
                                    'height':eBox_head_h height 'px',
                                    'margin-left':-(lebar eBoxPadding)/2 'px',
                                    'atas':nScrollTop (nWindow_h-height-eBoxPadding)/2 'px'});
            this.tools.setCss(this.tools.getId('gy_photoBox_main'),{'width':width 'px','height':height 'px'});
            //设置覆盖层的样式
            this.tools.setCss(this.tools.getId('gy_photoBox_cover'),{'height':nScrollTop doc.documentElement.clientHeight 'px'});
        },
        removeBox:function(){
            var doc = dokumen;
            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:function(){
            untuk(var n=0;n                 var src = this.oTarget[n].getAttribute('href'),
                    tajuk = this.oTarget[n].getAttribute('title');
                this.aBigimg_src.push(src);
                jika(!tajuk) tajuk = '';
                this.aTitle.push(title);
            }
        },
        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:function(){
            var _itu = ini,
                _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,
                'kejayaan':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();
// Tetingkap timbul muncul
                    _that.tools.setCss(_that.tools.getId('gy_photoBox'),{'visibility':'visible'});
If(_that.tools.getId('gy_photoBox_firstLoad')){
document.body.removeChild(_that.tools.getId('gy_photoBox_firstLoad'));
                 }
// Fungsi panggil balik dilaksanakan setiap kali menukar
If(typeof _that.opt.onChange == 'function'){
                     _that.opt.onChange({'src':_src,'index':_that.nIndex,'title':_that.aTitle[_that.nIndex]});
                                                                                                                                                                                                                                                                                                       },
                 'ralat':function(){
                                           setTimeout(function(){
                         _that.tools.setCss(eLoadingTips,{'display':'none'});
                     },200);
                       eImg.src = 'gyPhotoBox/error.png';
eTitle.innerHTML = 'Tiada gambar berkaitan';
                        _that.nImgWidth = 400;
                        _that.nImgHeight = 300;
                       _that.setBoxCss();
                   _that.tools.setCss(_that.tools.getId('gy_photoBox'),{'visibility':'visible'});
If(_that.tools.getId('gy_photoBox_firstLoad')){
document.body.removeChild(_that.tools.getId('gy_photoBox_firstLoad'));
                 }
                }
            });
},
          btnPrev:function(){
               var _itu = ini;
This.tools.getId('gy_photoBox_prev').onclick = function(){
                _that.nIndex--;
                _that.imgChange();
            }
        },
        btnSeterusnya:function(){
            var _itu = ini;
            this.tools.getId('gy_photoBox_next').onclick = function(){
                _that.nIndex ;
                _that.imgChange();
            }
        },
        keyEvent:function(){
            var _itu = ini;
            document.onkeydown = fungsi(e){
                var e = e || tingkap.acara;
                suis(e.Kod kunci){
                    kes 37:{
                        if(_that.nIndex != 0&&_that.tools.getId('gy_photoBox_prev')){
                            _that.nIndex--;
                            _that.imgChange();   
                        }   
                    };rehat;
                    kes 39 :{
                        if(_that.nIndex != (_that.nLen-1)&&_that.tools.getId('gy_photoBox_next')){
                            _that.nIndex ;
                            _that.imgChange();   
                        }           
                    };rehat;
                    kes 27:{
                        _that.removeBox();                           
                    };rehat;
                }
            }
        },
        /*
        @ src [String] 图片的地址
        @ kejayaan [Fungsi] 图片加载成功的回调函数
        @ ralat [Fungsi] 图片加载失败的回调函数
        */
        imgLoading:function(opt){
            var _img = Imej baharu(),
                _itu = ini;
            _img.onload = function(){
                _that.nImgWidth = this.width;
                _that.nImgHeight = this.height;
                if(typeof opt.success == 'function'){
                    setTimeout(function(){
                        opt.success();
                    },300);
                }
            }
            _img.onerror = function(){
                if(typeof opt.error){
                    opt.error();
                }           
            }
            // 注意:要放在onload事件下面,否则ie会出现BUG
            _img.src = opt.src;
        },
        firstLoad:function(src,panggilan balik){
            var _itu = ini,
                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(jenis panggilan balik == 'fungsi') {
                panggil balik();
            }
        },
        windowResize:function(){
            var _itu = ini,
                _pemasa = batal;
            // 函数节流
            window.onresize = function(){
                clearTimeout(_pemasa);
                _timer = setTimeout(function(){
                    jika( _that.tools.getId('gy_photoBox')){
                        _that.setBoxCss();
                    }
                },100);
            }       
        },
        alatan:function(){
            kembali{
                getEvent:function(e){
                    pulangkan e || tingkap.acara;
                },
                getTarget:function(e){
                    pulangkan e.sasaran || e.srcElement;
                },
                preventDefault:function(e){
                    e.preventDefault?e.preventDefault():e.returnValue = false;
                },
                getId:function(id){
                    kembalikan document.getElementById(id);
                },
                getCss:function(nod,nilai){
                    kembalikan node.currentStyle?node.currentStyle[value]:getComputedStyle(nod,null)[value];
                },
                setCss:function(nod,val){
                    untuk(var v dalam val){
                        node.style.cssText = ';' v ':' val[v];
                    }
                }
            }
        }()
    }
    window.LGY_photoBox = LGY_photoBox;
})();

最终效果图:

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn