>  기사  >  웹 프론트엔드  >  네이티브 자바스크립트로 그림팝업 인터랙티브 효과 구현_자바스크립트 능력

네이티브 자바스크립트로 그림팝업 인터랙티브 효과 구현_자바스크립트 능력

WBOY
WBOY원래의
2016-05-16 16:20:581283검색

【1】여러 변수를 선언할 때 var를 사용하는 것이 각 변수에 대해 var를 사용하는 것보다 훨씬 빠릅니다.

코드 복사 코드는 다음과 같습니다.
var sScrollTop = document.body.scrollTop || document.documentElement.scrollTop,
sWindow_h = document.documentElement.clientHeight,
t_h = parsInt(this.getCss(this.getId('gy_photoBox_head'),'height')),
Hold_h = sWindow_h - t_h - 20,
너비 = this.nImgWidth ,
높이 = this.nImgHeight

【2】Dom 이벤트 최적화, window.onresize 시 타이머 setTimeout을 정의하여 잦은 이벤트 호출을 방지할 수 있습니다

코드 복사 코드는 다음과 같습니다.
windowResize:함수(){
               var _that = 이,
                 _timer = null;
// 함수 조절
               window.onresize = function(){
> "                   _timer = setTimeout(function(){
If( _that.tools.getId('gy_photoBox')){
                         _that.setBoxCss();
                 }

},100); ~ }




[3] 이미지 로딩 처리 기능


코드 복사 코드는 다음과 같습니다.

/*
           @ src [String] 이미지 주소
​​​​​@success[함수] 이미지 로딩 성공을 위한 콜백 함수
​​​​​@오류 [함수] 이미지 로딩 실패시 콜백 함수
*/
          imgLoading:function(opt){
            var _img = 새 이미지(),
                 _저것 = 이;
​​​​​​​ _img.onload = function(){
                   _that.nImgWidth = this.width;
                   _that.nImgHeight = this.height;
If(opt.success 유형 == '함수'){
                                        setTimeout(function(){
                                       opt.success();
                     },300);
                }
            }
                _img.onerror = function(){
If(opt.error 유형){
                       opt.error();
~             }
|                 _img.src = opt.src;
}


소스코드:

코드 복사 코드는 다음과 같습니다.

/*
저자:laoguoyong
*/
(함수(){
/* ------------간단한 선택자------ --- -
@ 매개변수 [문자열]
​​-------------
★ - 아래 옵션만 지원됩니다 -★
@ 첫 번째 수준 선택기 지원: '#id', '.class', 'p'
등 @ '.class p', 'body span' 등 하위 항목 선택 지원
@ '.class>p', 'body>span' 등 하위 요소 선택 지원
​ --------------
@ return [배열]
*/
var 선택기 = 함수(str){
​​​​ //요소 배열 정의
var 요소 = [];
              /* 비공개 방식
​​​​------------*/
//id가 있는 요소를 반환합니다
         함수 _getId(id){
               return document.getElementById(id);
}
//해당 이름을 가진 요소를 반환합니다 - 요소
         함수 _getByClassName(className,parent){
            var class_array = [],
노드 = 상위 != 정의되지 않음&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
                reg = new RegExp("(^|\s)" className "(\s|$)");
for(var n=0,i=node.length;n If(reg.test(node[n].className)){
                       class_array.push(node[n]);
                }
            }
                return class_array;
}
//'#id','p','.class'와 같은 첫 번째 수준 선택
              // [배열] 반환
         함수 _getDom(s){
            var array_elem = [];
If (s.indexOf('#')==0){
                   array_elem.push(_getId(s.slice(1)));
            }
                 else if(s.indexOf('.')==0){
                  array_elem = array_elem.concat(_getByClassName(s.slice(1)));
            }
            그 외{
              var tag = document.getElementsByTagName(s);
for(var n=0,i=tag.length;n                        array_elem.push(tag[n]);
                }
            }
               return array_elem;
}
          /*
​​​​​ @arry_elm [배열]: ['.demo','p']와 같은 요소 배열, .demo 아래의 p 요소가 선택됩니다. 하위 항목을 선택할지 하위 항목을 선택할지는 두 번째 매개변수를 참조하세요. 설명
​​​​​@ r [String] - 선택 사항(전달되지 않은 경우 기본값은 하위 항목을 선택하는 것임): '>', 하위 요소를 선택합니다.
        -------------
        @ return [배열]
        */
        함수 _query(array_elem,r){
            var 노드 = array_elem,
                type_name = node[0].match(/#/)?'id_' node[0].slice(1):node[0].match(/./)?'className_' node[0].slice(1 ):'tagName_' 노드[0],
                자식 = _getDom(노드[1]),
                유형 = 유형_이름.split('_'),
                len = document.getElementsByTagName('*').length,
                reg = new RegExp("(^|\s)" type[1] "(\s|$)");;
            for(var i=0,j=child.length;i                 var par = child[i].parentNode;
                for(var n=0;n                     if(par.nodeType == 9){
                        휴식;
                    }
                    if(reg.test(par[type[0]])){
                        elem.push(child[i]);
                        부서지다;                   
                    }그밖에{
                        if(r == '>') break;
                        par = par.parentNode;
                    }       
                }
            }
        }
        /* 接口
        --------*/
        var elemStr = str.replace(/(^s )|(s $)/,'');
        if(document.querySelectorAll){
            var dom = document.querySelectorAll(elemStr);
            for(var n=0,len=dom.length;n                 elem.push(dom[n]);
            }
        }그밖에{
            var    분할 = /[>s]/g.exec(elemStr);
            if(분할){
                var node = elemStr.split(split[0]);
                _query(노드,분할[0]);
            }그밖에{
                elem = elem.concat( _getDom(elemStr) );
            }
}
         요소 반환
}
/* 팝업창 함수 생성자
​ ----------*/
기능 LGY_photoBox(옵션){
This.opt = 옵션;
This.oTarget = option.target 유형 == 'object'?option.target:selector(option.target);
If(!this.oTarget) return;
This.nLen = this.oTarget.length; //총 개수
This.aBigimg_src = []; //큰 이미지 데이터 배열
This.aTitle = []; //제목 데이터 배열
This.nIndex = 0; //인덱스
This.nImgWidth = 0; //동적으로 이미지의 너비를 구합니다
This.nImgHeight = 0; //동적으로 사진의 높이를 구합니다
This.nDelay = 0.2;
This.intit();
}
LGY_photoBox.prototype = {
         intit:function(){
               var _that = this;
This.getData();
for(var n=0;n This.oTarget[n].index = n;
This.oTarget[n].onclick = 함수(e){
                      _that.createCover();
                var e = _that.tools.getEvent(e),
대상 = _that.tools.getTarget(e);
// 롤링 스트립 없이 검색 페이지를 설정합니다.
                   _that.tools.setCss(document.documentElement,{'height':'100%','overflow-y':'hidden','overflow-x':'hidden'});
// 현재 인덱스를 가져옵니다
                      _that.nIndex = this.index;
//1차 판단
                     _that.firstLoad(_that.aBigimg_src[_that.nIndex], function(){
//구조 삽입
                          _that.createBoxDom();
>                                                      That.tools.getId('gy_photoBox_close').onclick = function(){
                    _that.removeBox();                                 | // 왼쪽 및 오른쪽 버튼이 표시되는지 확인
_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:함수(){
            // 创建覆盖层
            var    doc = 문서,
                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:함수(){
            var    doc = 문서,
                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,
                너비 = this.nImgWidth ,
                높이 = this.nImgHeight;
            // 경고('nWindow_h:' nWindow_h '-' 'eBoxPadding:' eBoxPadding '-' 'eBox_head_h:' eBox_head_h);
            // 图文大小超过可见范围,进行缩放
            if(this.nImgHeight>hold_h){
                높이 = 홀드_h,
                width = Math.ceil(this.nImgWidth*(height/this.nImgHeight));
            }
            //设置盒子가 整个页면居中
            this.tools.setCss(eBox,{'width':width 'px',
                                    '높이':eBox_head_h 높이 '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':width 'px','height':height 'px'});
            //设置覆盖层的样式
            this.tools.setCss(this.tools.getId('gy_photoBox_cover'),{'height':nScrollTop doc.documentElement.clientHeight 'px'});
        },
        제거박스:함수(){
            var doc = 문서;
            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:함수(){
            for(var n=0;n                 var src = this.oTarget[n].getAttribute('href'),
                    title = this.oTarget[n].getAttribute('title');
                this.aBigimg_src.push(src);
                if(!title) 제목 = '';
                this.aTitle.push(제목);
            }
        },
        btnIsShow:함수(){
            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:함수(){
            var _that = 이것,
                _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,
                '성공':함수(){
                    _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();
// 팝업창이 나타납니다
                    _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'));
                 }
// 전환할 때마다 실행되는 콜백 함수
If(typeof _that.opt.onChange == '함수'){
                    _that.opt.onChange({'src':_src,'index':_that.nIndex,'title':_that.aTitle[_that.nIndex]});
~                                                                  },
                 '오류':기능(){
                                        setTimeout(function(){
                       _that.tools.setCss(eLoadingTips,{'display':'none'});
                    },200);
                     eImg.src = 'gyPhotoBox/error.png';
eTitle.innerHTML = '관련 사진 없음';
                       _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 _that = this;
This.tools.getId('gy_photoBox_prev').onclick = function(){
                _that.n색인--;
                _that.imgChange();
            }
        },
        btnNext:함수(){
            var _that = this;
            this.tools.getId('gy_photoBox_next').onclick = function(){
                _that.n인덱스 ;
                _that.imgChange();
            }
        },
        키이벤트:함수(){
            var _that = this;
            document.onkeydown = 함수(e){
                var e = e || window.event;
                스위치(e.keyCode){
                    사례 37:{
                        if(_that.nIndex != 0&&_that.tools.getId('gy_photoBox_prev')){
                            _that.n색인--;
                            _that.imgChange();   
                        }   
                    };휴식;
                    사례 39 :{
                        if(_that.nIndex != (_that.nLen-1)&&_that.tools.getId('gy_photoBox_next')){
                            _that.n인덱스 ;
                            _that.imgChange();   
                        }           
                    };휴식;
                    사례 27:{
                        _that.removeBox();                           
                    };휴식;
                }
            }
        },
        /*
        @ src [String] 사진의 위치
        @ 성공 [함수] 图文加载成功的回调函数
        @ 오류 [기능] 图文加载失败的回调函数
        */
        imgLoading:함수(옵션){
            var _img = 새 이미지(),
                _저것=이것;
            _img.onload = 함수(){
                _that.nImgWidth = this.width;
                _that.nImgHeight = this.height;
                if(opt.success 유형 == '함수'){
                    setTimeout(함수(){
                        opt.success();
                    },300);
                }
            }
            _img.onerror = 함수(){
                if(opt.error 유형){
                    opt.error();
                }           
            }
            // 참고: 要放onload事件下面,否则ie会出现BUG
            _img.src = opt.src;
        },
        firstLoad:함수(src,callback){
            var _that = 이것,
                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(콜백 유형 == '함수') {
                콜백();
            }
        },
        windowResize:함수(){
            var _that = 이것,
                _timer = null;
            // 函数节流
            window.onresize = 함수(){
                ClearTimeout(_timer);
                _timer = setTimeout(함수(){
                    if( _that.tools.getId('gy_photoBox')){
                        _that.setBoxCss();
                    }
                },100);
            }       
        },
        도구:함수(){
            복귀{
                getEvent:함수(e){
                    전자를 돌려줘 || window.event;
                },
                getTarget:함수(e){
                    e.target을 반환 || e.srcElement;
                },
                PreventDefault:function(e){
                    e.preventDefault?e.preventDefault():e.returnValue = false;
                },
                getId:함수(id){
                    return document.getElementById(id);
                },
                getCss:함수(노드,값){
                    return node.currentStyle?node.currentStyle[값]:getCompulatedStyle(node,null)[값];
                },
                setCss:함수(노드,발){
                    for(var v in val){
                        node.style.cssText = ';' v ':' val[v];
                    }
                }
            }
        }()
    }
    window.LGY_photoBox = LGY_photoBox;
})();

最终效果图:

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.