【1】 Use var para declarar várias variáveis, o que é muito mais rápido do que usar o VAR para cada variável
A cópia do código é a seguinte:
var sscrolltop = document.body.scrolltop || document.documentElement.scrolltop,
swindow_h = document.documentElement.clientHeight,
t_h = parseint (this.getcss (this.getId ('gy_photobox_head'), 'altura')),
hold_h = swindow_h - t_h - 20,
largura = this.nimgwidth,
altura = this.nimghEight;
[2] Otimização de eventos DOM, quando Window.OnResize, defina um cronômetro e o Settimeout para impedir que chamadas frequentes aconteçam
A cópia do código é a seguinte:
WindowResize: function () {
var _ que this, este,
_timer = null;
// Função de função
window.onResize = function () {
ClearTimeout (_timer);
_timer = setTimeout (function () {
if (_that.tools.getid ('gy_photobox')) {
_athat.setBoxcss ();
}
}, 100);
}
}
【Três】 Função de processamento de carregamento de imagem
A cópia do código é a seguinte:
/*
@ src [string] endereço de imagem
@ Sucesso [função] Função de retorno de chamada para carregamento de imagem bem -sucedido
@ Error [função] Função de retorno de chamada para carregamento de imagem com falha
*/
imgloading: function (opt) {
var _img = new Image (),
_ que = this;
_img.onload = function () {
_athat.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: ele deve ser colocado sob o evento Onload, caso contrário, o IE terá um bug
_img.src = opt.src;
}
código -fonte:
A cópia do código é a seguinte:
/*
Autor: Laoguoyong
*/
(função(){
/* ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@ Parâmetros [string]
-----------------------------------------
★-Apenas as seguintes seleções são suportadas-★
@ Suportar seletores de primeiro nível: como '#id', 'classe', 'p'
@ Apoie a seleção descendente, como '.class p', 'body span'
@ Apoiar a seleção de elementos filhos, como '.class> p', 'corpo> span'
------------------------------------------
@ Return [Array]
*/
var selettor = function (str) {
// define uma variedade de elementos
var elem = [];
/* Método privado
-----------------------*/
// elemento de retorno que é id
função _getId (id) {
retornar document.getElementById (id);
}
// retorna o elemento com este elemento de nome
função _getbyclassName (className, pai) {
var class_array = [],
node = pai!
reg = new regexp ("(^| // s)"+className+"(// s | $)");
for (var n = 0, i = node.length; n <i; n ++) {
if (reg.test (nó [n] .className)) {
Class_array.push (nó [n]);
}
}
retornar classe_array;
}
// seleção de nível 1, como '#id', 'p', 'classe'
// Retornar [Array]
função _getDom (s) {
var Array_Elem = [];
if (s.IndexOF ('#') == 0) {
Array_Elem.push (_GetId (s.slice (1)));
}
caso contrário, if (s.IndexOF ('.') == 0) {
Array_Elem = Array_Elem.Concat (_GetbyClassName (S.Slice (1)));
}
outro{
var tag = document.getElementsByTagName (s);
for (var n = 0, i = tag.length; n <i; n ++) {
Array_Elem.push (tag [n]);
}
}
retornar array_elem;
}
/*
@arry_elm [Array]: Array do elemento, como ['.demo', 'p'], selecione o elemento P abaixo .Demo. Quanto a escolher descendentes ou descendentes, consulte a explicação do segundo parâmetro
@r [string] - Opcional (o padrão é selecionar descendentes se você não passar): '>', é o elemento de selecionar descendentes;
--------------------------------------
@ Return [Array]
*/
função _Query (Array_Elem, r) {
var node = Array_Elem,
type_name = node [0] .match (//#/)? 'id _'+nó [0] .slice (1): node [0] .match (//./)?
criança = _getDom (nó [1]),
type = type_name.split ('_'),
len = document.getElementsByTagName ('*'). Length,
reg = novo regexp ("(^| // s)"+tipo [1]+"(// s | $)") ;;
for (var i = 0, j = child.length; i <j; i ++) {
var par = criança [i] .parentNode;
for (var n = 0; n <len; n ++) {
if (par.nodeType == 9) {
quebrar;
}
if (reg.test (par [tipo [0]])) {
elem.push (criança [i]);
quebrar;
}outro{
if (r == '>') quebra;
par = par.parentNode;
}
}
}
}
/* Interface
------------------------*/
var eleMstr = str.replace (/(^/s+) | (/s+$)/, '');
if (document.QuerySelectorAll) {
var dom = document.QuerySelectorAll (elemstr);
for (var n = 0, len = dom.length; n <len; n ++) {
elem.push (dom [n]);
}
}outro{
var split =////s ]/g.exec(Elemstr);
if (split) {
var node = elemstr.split (dividido [0]);
_Query (nó, dividido [0]);
}outro{
elem = elem.concat (_getDom (elemstr));
}
}
retornar elem;
}
/* Construtor de função pop-up
------------------------*/
função lgy_photobox (opção) {
this.opt = option;
this.oTarget = typeof option.target == 'object'? Option.Target: Selector (option.Target);
if (! this.oTarget) retornar;
this.nlen = this.otarget.length; // Número total
this.abigimg_src = []; // Array de dados de imagem grande
this.atitle = []; // Array de dados de título
this.nindex = 0; //Índice
this.nimgwidth = 0; // obtenha dinamicamente a largura da imagem
this.nimghEight = 0; // Obtenha dinamicamente a altura da imagem
this.ndelay = 0,2;
this.Intit ();
}
Lgy_photobox.prototype = {
intit: function () {
var _That = this;
this.getData ();
for (var n = 0; n <this.nlen; 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);
// Nenhuma barra de rolagem aparece na página de navegação de configurações
_athat.tools.setcss (document.documentElement, {'altura': '100%', 'overflow-y': 'Hidden', 'Overflow-x': 'Hidden'});
// Obtenha o índice naquele momento
_athat.nindex = this.index;
// Primeiro julgamento
_athat.firstload (_athat.abigimg_src [_that.nindex], function () {
// Inserir estrutura
_that.createboxdom ();
//encerramento
_that.tools.getid ('gy_photobox_close'). OnClick = function () {
_athat.RemoveBox ();
}
// Juiz Botões esquerdo e direito para exibir
_athat.btnisshow ();
// Anterior
_athat.btnPrev ();
// Próximo
_that.btnNext ();
// Carregar a imagem
_athat.imgChange (_athat.abigimg_src [_that.nindex]);
});
// Redefinir tamanho da janela
_that.windowResize ();
// Eventos de teclado
_athat.keyEvent ();
// Pare de saltar
retornar falso;
}
}
},
CreateBoxdom: function () {
var doc = document,
extml = '',
boxhtml = doc.createElement ('div');
boxhtml.id = 'gy_photobox';
doc.body.appendChild (boxhtml);
if (typeof this.opt.appendhtml == 'string') {
extml = this.opt.appendhtml;
}
boxhtml.innerhtml = '<div id = "gy_photobox_prev"> </div>'+
'<div id = "gy_photobox_next"> </div>'+
'<span id = "gy_photobox_close"> </span>'+
'<div id = "gy_photobox_head">'+extml+'</div>'+
'<div id = "gy_photobox_main">'+
'<img id = "gy_photobox_img_loading" src = "http://www.pconline.com.cn/blank.gif"/>'+
'<img id = "gy_photobox_img" />'+
'<div id = "gy_photobox_infor">'+
'<span id = "gy_photobox_num">'+
'<Strong id = "gy_photobox_index"> </strong>'+
'/'+this.nlen+
'</span>'+
'<p id = "gy_photobox_title"> </p>'+
'</div>'+
'</div>';
},
CreateCover: function () {
// Crie sobreposição
var doc = document,
Coverhtml = doc.createElement ('div');
Coverhtml.id = 'gy_photobox_cover';
doc.body.appendChild (Coverhtml);
// Defina o estilo da camada de sobreposição
this.tools.setcss (this.tools.getid ('gy_photobox_cover'), {'altura' :( 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').
ebox = this.tools.getid ('gy_photobox'),
eboxpadding = 10,
hold_h = nwindow_h - eboxpadding - 50 - ebox_head_h,
largura = this.nimgwidth,
altura = this.nimghEight;
// alert ('nwindow_h:'+nwindow_h+'-'+'eboxpadding:'+eboxpadding+'-'+'ebox_head_h:'+ebox_head_h);
// O tamanho da imagem excede a faixa visível, zoom
if (this.nimgheight> hold_h) {
altura = hold_h,
largura = math.ceil (this.nimgwidth*(altura/this.nimghight));
}
// Defina a caixa centrada durante toda a página
this.tools.setcss (ebox, {'width': width+'px',
'altura': ebox_head_h + altura + 'px',
'margem-esquerda' :-( largura+eboxpadding)/2+'px',
'top': nscrolltop+(nwindow_h-tex-eboxpadding)/2+'px'});
this.tools.setcss (this.tools.getid ('gy_photobox_main'), {'width': width + 'px', 'altura': altura + 'px'});
// Defina o estilo da camada de sobreposição
this.tools.setcss (this.tools.getid ('gy_photobox_cover'), {'altura': nscrolltop+doc.documentElement.clientHeight+'px'});
},
RemowBox: 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, {'altura': 'auto', 'overflow-y': 'auto', '_ overflow-y': 'roll', 'overflow-x': 'auto'});
},
getData: function () {
for (var n = 0; n <this.nlen; 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 (título);
}
},
btnisshow: function () {
this.tools.setcss (this.tools.getid ('gy_photobox_prev'), {'display': 'bloqueio'});
this.tools.setcss (this.tools.getid ('gy_photobox_next'), {'display': 'bloquear'});
if (this.nindex == 0) this.tools.setcss (this.tools.getId ('gy_photobox_prev'), {'display': 'nenhum'});
if (this.nindex == (this.nlen-1)) this.tools.setcss (this.tools.getId ('gy_photobox_next'), {'display': 'nenhum'});
},
imgchange: function () {
var _ que this, este,
_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');
// Mostrar imagem de carregamento
this.tools.setcss (EloadingTips, {'Display': 'Block'});
this.tools.setcss (einfor, {'display': 'nenhum'});
// Juiz Botões esquerdo e direito para exibir
this.btnisshow ();
// Processamento de carregamento de imagem
this.imgloading ({
'src': _ src,
'Sucesso': function () {
_athat.tools.setcss (eloadingtips, {'display': 'None'});
_athat.tools.setcss (einfor, {'display': 'Block'});
// Defina o caminho de imagem real, título, número atual da página
eimg.src = _src;
etitle.innerhtml = _that.atitle [_athat.nindex];
_that.tools.getId ('gy_photobox_index'). innerhtml = (_that.nindex+1);
// Defina o estilo
_athat.setBoxcss ();
// A janela pop-up aparece
_that.tools.setcss (_athat.tools.getId ('gy_photobox'), {'visibilidade': 'visível'});
if (_that.tools.getid ('gy_photobox_firstload')) {
document.body.removechild (_that.tools.getId ('gy_photobox_firstload'));
}
// a função de retorno de chamada executada toda vez que o interruptor é
if (typeof _that.opt.onchange == 'function') {
_athat.opt.onchange ({'src': _ src, 'index': _ that.nindex, 'title': _ that.atitle [_athat.nindex]});
}
},
'Error': function () {
setTimeout (function () {
_athat.tools.setcss (eloadingtips, {'display': 'None'});
}, 200);
eimg.src = 'gyphotobox/error.png';
etitle.innerhtml = 'sem imagens relacionadas';
_that.nimgwidth = 400;
_athat.nimghEight = 300;
_athat.setBoxcss ();
_that.tools.setcss (_athat.tools.getId ('gy_photobox'), {'visibilidade': 'visível'});
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 () {
_athat.nindex--;
_athat.imgChange ();
}
},
btnNext: function () {
var _That = this;
this.tools.getid ('gy_photobox_next'). OnClick = function () {
_that.nindex ++;
_athat.imgChange ();
}
},
keyEvent: function () {
var _That = this;
document.onkeydown = function (e) {
var e = e || Window.Event;
Switch (e.KeyCode) {
Caso 37: {
if (_that.nindex! = 0 && _ that.tools.getid ('gy_photobox_prev')) {
_athat.nindex--;
_athat.imgChange ();
}
};quebrar;
Caso 39: {
if (_athat.nindex! = (_athat.nlen-1) && _ that.tools.getid ('gy_photobox_next')) {
_that.nindex ++;
_athat.imgChange ();
}
};quebrar;
Caso 27: {
_athat.RemoveBox ();
};quebrar;
}
}
},
/*
@ src [string] endereço de imagem
@ Sucesso [função] Função de retorno de chamada para carregamento de imagem bem -sucedido
@ Error [função] Função de retorno de chamada para carregamento de imagem com falha
*/
imgloading: function (opt) {
var _img = new Image (),
_ que = this;
_img.onload = function () {
_athat.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: ele deve ser colocado sob o evento Onload, caso contrário, o IE terá um bug
_img.src = opt.src;
},
FirstLoad: function (src, retorno de chamada) {
var _ que this, este,
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 de retorno de chamada == 'função') {
ligar de volta();
}
},
WindowResize: function () {
var _ que this, este,
_timer = null;
// Função de função
window.onResize = function () {
ClearTimeout (_timer);
_timer = setTimeout (function () {
if (_that.tools.getid ('gy_photobox')) {
_athat.setBoxcss ();
}
}, 100);
}
},
Ferramentas: function () {
retornar{
getEvent: function (e) {
retornar e || Window.Event;
},
getTarget: function (e) {
Retornar E.Target || E.Srcelement;
},
PreventDefault: function (e) {
E.PreventDefault? E.PreventDefault (): e.returnValue = false;
},
getId: function (id) {
retornar document.getElementById (id);
},
getcss: function (nó, valor) {
Return Node.CurrentStyle? Node.CurrentStyle [Value]: GetComputedStyle (nó, nulo) [Value];
},
setcss: function (nó, val) {
para (var V em val) {
node.style.csStext += ';' +v +':' +val [v];
}
}
}
} ()
}
window.lgy_photobox = lgy_photobox;
}) ();
Renderização final: