您好,欢迎访问一九零五行业门户网

原生javascript实现图片弹窗交互效果_javascript技巧

【一】用var 声明多个变量,比每个变量都用var快多了
复制代码 代码如下:
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,
    width = this.nimgwidth ,
    height = this.nimgheight;
【二】dom事件优化,在 window.onresize时,定义个定时器,settimeout,可以防止事件频繁调用
复制代码 代码如下:
windowresize:function(){
            var _that = this,
                _timer = null;
            // 函数节流
            window.onresize = function(){
                cleartimeout(_timer);
                _timer = settimeout(function(){
                    if( _that.tools.getid('gy_photobox')){
                        _that.setboxcss();
                    }                },100);
            }       
        }
【三】图片加载的处理函数
复制代码 代码如下:
/*
        @ src [string] 图片的地址
        @ success [function] 图片加载成功的回调函数
        @ error [function] 图片加载失败的回调函数
        */
        imgloading:function(opt){
            var _img = new image(),
                _that = this;
            _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;
        }
源代码:
复制代码 代码如下:
/*
author:laoguoyong
*/
(function(){
    /* -------------------------简单的选择器-----------------------
    @ 参数 [string]
    ---------------------------------------
    ★-只支持以下选择-★
    @ 支持一级选择器:如'#id','.class','p'
    @ 支持后代选择,如 '.class p','body span'
    @ 支持子元素选择,如 '.class>p','body>span'
    ----------------------------------------
    @ return [array]
    */
    var selector = function(str){
        // 定义元素数组
        var elem = [];
        /* 私有方法
        ------------------------*/
        //返回是id的元素
        function _getid(id){
            return document.getelementbyid(id);
        }
        //返回存在此类名的元素-元素
        function _getbyclassname(classname,parent){
            var class_array = [],
                node = 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(node[n].classname)){
                    class_array.push(node[n]);
                }
            }
            return class_array;
        }
        //一级选择,如 '#id','p','.class'
        // return [array]
        function _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)));
            }
            else{
                var tag = document.getelementsbytagname(s);
                for(var n=0,i=tag.length;n                    array_elem.push(tag[n]);
                }
            }
            return array_elem;
        }
        /*
        @ arry_elm [array] : 元素数组,如 ['.demo','p'] ,选择的是.demo下面的p元素,至于是选择后代还是子代,请看第2个参数解释
        @ r [string] -可选(不传默认为选择后代): '>',是选择子代元素;
        --------------------------
        @ return [array]
        */
        function _query(array_elem,r){
            var node = array_elem,
                type_name = node[0].match(/\#/)?'id_'+node[0].slice(1):node[0].match(/\./)?'classname_'+node[0].slice(1):'tagname_'+node[0],
                child = _getdom(node[1]),
                type = type_name.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){
                        break;
                    }
                    if(reg.test(par[type[0]])){
                        elem.push(child[i]);
                        break;                   
                    }else{
                        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]);
            }
        }else{
            var    split = /[\>\s]/g.exec(elemstr);
            if(split){
                var node = elemstr.split(split[0]);
                _query(node,split[0]);
            }else{
                elem = elem.concat( _getdom(elemstr) );
            }
        }
        return elem;
    }
    /* 弹窗功能构造函数
    -----------------------*/
    function 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; //总个数
        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 = function(e){
                    _that.createcover();
                    var e = _that.tools.getevent(e),
                        target = _that.tools.gettarget(e);
                    // 设置浏页面没有滚动条出现
                    _that.tools.setcss(document.documentelement,{'height':'100%','overflow-y':'hidden','overflow-x':'hidden'});
                    // 获取当时索引
                    _that.nindex = this.index;
                    //首次判断
                    _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:function(){
            // 创建覆盖层
            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:function(){
            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,
                width = this.nimgwidth ,
                height = this.nimgheight;
            // alert('nwindow_h:'+nwindow_h+'-'+'eboxpadding:'+eboxpadding+'-'+'ebox_head_h:'+ebox_head_h);
            // 图片大小超过可见范围,进行缩放
            if(this.nimgheight>hold_h){
                height = hold_h,
                width = math.ceil(this.nimgwidth*(height/this.nimgheight));
            }
            //设置盒子在整个页面居中
            this.tools.setcss(ebox,{'width':width+'px',
                                    'height':ebox_head_h + height + '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'});
        },
        removebox:function(){
            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:function(){
            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) title = '';
                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 _that = this,
                _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,
                'success':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();
                    // 弹窗呈现
                    _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 == 'function'){
                        _that.opt.onchange({'src':_src,'index':_that.nindex,'title':_that.atitle[_that.nindex]});
                    }
                },
                'error':function(){
                    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.nindex--;
                _that.imgchange();
            }
        },
        btnnext:function(){
            var _that = this;
            this.tools.getid('gy_photobox_next').onclick = function(){
                _that.nindex++;
                _that.imgchange();
            }
        },
        keyevent:function(){
            var _that = this;
            document.onkeydown = function(e){
                var e = e || window.event;
                switch(e.keycode){
                    case 37:{
                        if(_that.nindex != 0&&_that.tools.getid('gy_photobox_prev')){
                            _that.nindex--;
                            _that.imgchange();   
                        }   
                    };break;
                    case 39 :{
                        if(_that.nindex != (_that.nlen-1)&&_that.tools.getid('gy_photobox_next')){
                            _that.nindex++;
                            _that.imgchange();   
                        }           
                    };break;
                    case 27:{
                        _that.removebox();                           
                    };break;
                }
            }
        },
        /*
        @ src [string] 图片的地址
        @ success [function] 图片加载成功的回调函数
        @ error [function] 图片加载失败的回调函数
        */
        imgloading:function(opt){
            var _img = new image(),
                _that = this;
            _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,callback){
            var _that = this,
                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') {
                callback();
            }
        },
        windowresize:function(){
            var _that = this,
                _timer = null;
            // 函数节流
            window.onresize = function(){
                cleartimeout(_timer);
                _timer = settimeout(function(){
                    if( _that.tools.getid('gy_photobox')){
                        _that.setboxcss();
                    }
                },100);
            }       
        },
        tools:function(){
            return{
                getevent:function(e){
                    return e || window.event;
                },
                gettarget:function(e){
                    return e.target || e.srcelement;
                },
                preventdefault:function(e){
                    e.preventdefault?e.preventdefault():e.returnvalue = false;
                },
                getid:function(id){
                    return document.getelementbyid(id);
                },
                getcss:function(node,value){
                    return node.currentstyle?node.currentstyle[value]:getcomputedstyle(node,null)[value];
                },
                setcss:function(node,val){
                    for(var v in val){
                        node.style.csstext += ';'+ v +':'+val[v];
                    }
                }
            }
        }()
    }
    window.lgy_photobox = lgy_photobox;
})();
最终效果图:
其它类似信息

推荐信息