【1】 Use VAR para declarar múltiples variables, que es mucho más rápido que usar VAR para cada variable
La copia del código es la siguiente:
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,
ancho = this.nimgWidth,
altura = this.nimgheight;
[2] Optimización de eventos DOM, cuando Window.enrese, defina un temporizador y setTimeOut para evitar que ocurran llamadas frecuentes
La copia del código es la siguiente:
WindowResize: function () {
var _THAT = esto,
_Timer = null;
// Función de estrangulamiento
window.onresize = function () {
ClearTimeOut (_Timer);
_timer = setTimeOut (function () {
if (_that.tools.getid ('gy_photobox')) {
_THAT.SetBOXCSS ();
}
}, 100);
}
}
【Función de procesamiento de carga de tres imágenes】
La copia del código es la siguiente:
/*
@ dirección de imagen src [cadena]
@ Función de devolución de llamada @ Success [Función] para una carga de imagen exitosa
@ Error [función] función de devolución de llamada para la carga de imagen fallida
*/
Imgloading: function (opt) {
var _img = nueva imagen (),
_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 ();
}
}
// NOTA: debe colocarse debajo del evento Onload, de lo contrario, el IE tendrá un error
_img.src = opt.src;
}
Código fuente:
La copia del código es la siguiente:
/*
Autor: Lauguoyong
*/
(función(){
/* -------------------------------------------------------------------------------------------------------
@ Parámetros [cadena]
---------------------------------------
★-Solo se admiten las siguientes selecciones- ★
@ Soporte de selectores de primer nivel: como '#id', '. Class', 'P'
@ Apoyar la selección descendiente, como '.class P', 'Body Span'
@ Soporte de selección de elementos infantiles, como '.class> p', 'cuerpo> span'
----------------------------------------
@ return [array]
*/
var selector = function (str) {
// Defina una variedad de elementos
var elem = [];
/* Método privado
---------------------*/
// Elemento de retorno que es ID
función _getId (id) {
return document.getElementById (id);
}
// Devuelve el elemento con este elemento de nombre
función _getByClassName (classname, parent) {
var class_array = [],
nodo = parent! = Undefined && parent.nodeType == 1?
reg = new Regexp ("(^| // s)"+classname+"(// s | $)");
para (var n = 0, i = node.length; n <i; n ++) {
if (reg.test (nodo [n] .classname)) {
class_array.push (nodo [n]);
}
}
return class_array;
}
// Selección de nivel 1, como '#id', 'P', '. Clase'
// return [matriz]
función _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)));
}
demás{
var etiqueta = document.getElementsBytagName (s);
para (var n = 0, i = tag.length; n <i; n ++) {
array_elem.push (etiqueta [n]);
}
}
return array_elem;
}
/*
@ARRY_ELM [Array]: Array de elementos, como ['.Demo', 'P'], seleccione el elemento P a continuación .Demo. En cuanto a si elegir descendientes o descendientes, consulte la segunda explicación del parámetro
@R [String] - Opcional (predeterminado es seleccionar descendientes si no pasa): '>', es el elemento de selección de descendientes;
------------------------------------
@ return [array]
*/
función _query (array_elem, r) {
var nodo = array_elem,
type_name = nodo [0] .match (//#/)? 'id _'+nodo [0] .slice (1): nodo [0] .match (//./)? 'classname _'+nodo [0] .slice (1): 'tagName _'+nodo [0],,
niño = _getdom (nodo [1]),
type = type_name.split ('_'),
len = document.getElementsBytagName ('*'). Longitud,
reg = new Regexp ("(^| // s)"+Tipo [1]+"(// s | $)") ;;
para (var i = 0, j = child.length; i <j; i ++) {
var par = niño [i] .ParentNode;
para (var n = 0; n <len; n ++) {
if (par.nodeType == 9) {
romper;
}
if (reg.test (par [type [0]])) {
elem.push (niño [i]);
romper;
}demás{
if (r == '>') break;
par = par.parentNode;
}
}
}
}
/* Interfaz
----------------------*/
var elemstr = str.replace (/(^/s+) | (/s+$)/, '');
if (document.QuerySelectorAll) {
var dom = document.QuerySelectorAll (ElemStr);
para (var n = 0, len = dom.length; n <len; n ++) {
elem.push (dom [n]);
}
}demás{
var split = /fice//sfont>/g.exec(elemstr);
if (split) {
var nodo = elemstr.split (dividir [0]);
_Query (nodo, dividido [0]);
}demás{
elem = elem.concat (_getdom (elemstr));
}
}
regresar elem;
}
/* Constructor de funciones emergentes
----------------------*/
función lgy_photobox (opción) {
this.opt = opción;
this.otarget = typeof option.target == 'object'? opcion.target: selector (option.target);
if (! this.otarget) return;
this.nlen = this.otarget.length; // número total
this.abigimg_src = []; // matriz de datos de imágenes grandes
this.atitle = []; // matriz de datos de títulos
this.nindex = 0; //Índice
this.nimgWidth = 0; // Obtén dinámicamente el ancho de la imagen
this.nimgheight = 0; // Obtén dinámicamente la altura de la imagen
this.ndelay = 0.2;
this.intit ();
}
Lgy_photobox.prototype = {
intit: functer () {
var _that = this;
this.getData ();
para (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);
// no aparece una barra de desplazamiento en la página de navegación de configuración
_that.tools.setcss (document.documentelement, {'altura': '100%', 'desbordamiento-y': 'oculto', 'desbordamiento-x': 'oculto'});
// Obtener el índice en ese momento
_that.nindex = this.index;
// Primer juicio
_that.firstload (_that.abigimg_src [_that.nindex], function () {
// Insertar estructura
_THAT.CreateBoxDom ();
//cierre
_that.tools.getid ('gy_photobox_close'). onClick = function () {
_that.removeBox ();
}
// juzga los botones izquierdo y derecho para mostrar
_THAT.BTNISSHOW ();
// Anterior
_THAT.BTNPREV ();
// Próximo
_THAT.BTNNEXT ();
// Carga la imagen
_that.imgchange (_that.abigimg_src [_that.nindex]);
});
// Restablecer el tamaño de la ventana
_that.WindowResize ();
// Eventos de teclado
_THAT.KeyEvent ();
// Stop Jump
devolver falso;
}
}
},
createboxdom: function () {
var doc = documento,
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 = '<div id = "gy_photobox_prev"> </div>'++
'<div id = "gy_photobox_next"> </div>'++
'<span id = "gy_photobox_close"> </span>'+
'<div id = "gy_photobox_head">'+exhtml+'</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 () {
// Crear superposición
var doc = documento,
coverHtml = doc.createElement ('div');
coverHtml.id = 'gy_photobox_cover';
doc.body.appendchild (coverhtml);
// Establecer el estilo de la capa superpuesta
this.tools.setcss (this.tools.getid ('gy_photobox_cover'), {'altura' :( doc.body.scrolltop || doc.documentelement.scrolltop)+(doc.documentelement.clientheight)+'px'});
},
setboxcss: function () {
var doc = documento,
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,
ancho = this.nimgWidth,
altura = this.nimgheight;
// alerta ('nwindow_h:'+nwindow_h+'-'+'eboxpadding:'+eboxpadding+'-'+'ebox_head_h:'+ebox_head_h);
// El tamaño de la imagen excede el rango visible, Zoom
if (this.nimgheight> hold_h) {
altura = Hold_h,
ancho = math.ceil (this.nimgWidth*(altura/this.nimgheight));
}
// Establecer el cuadro centrado en toda la página
this.tools.setcss (ebox, {'width': width+'px',
'altura': ebox_head_h + altura + 'px',
'Margin-Left' :-( Ancho+EboxPadding)/2+'Px',
'top': nscrolltop+(nwindow_h-height-eboxpadding)/2+'px'});
this.tools.setcss (this.tools.getid ('gy_photobox_main'), {'ancho': ancho + 'px', 'altura': altura + 'px'});
// Establecer el estilo de la capa superpuesta
this.tools.setcss (this.tools.getid ('gy_photobox_cover'), {'altura': nscrolltop+doc.documentelement.clientheight+'px'});
},
removeBox: function () {
var doc = documento;
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', 'desbordamiento-y': 'auto', '_ desbordamiento-y': 'scroll', 'overflow-x': 'auto'});
},
getData: function () {
para (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: functer () {
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 = esto,
_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 imagen de carga
this.tools.setcss (EloadingTips, {'Display': 'Block'});
this.tools.setcss (eInfor, {'display': 'none'});
// juzga los botones izquierdo y derecho para mostrar
this.btnisshow ();
// Procesamiento de carga de imágenes
this.imgLoading ({
'src': _ src,
'éxito': function () {
_that.tools.setcss (EloadingTips, {'Display': 'Ninguno'});
_that.tools.setcss (eInfor, {'display': 'block'});
// Establecer la ruta de imagen real, título, número de página actual
eimg.src = _src;
etitle.innerhtml = _that.atitle [_that.nindex];
_that.tools.getID ('gy_photobox_index'). innerhtml = (_that.nindex+1);
// Estilo establecido
_THAT.SetBOXCSS ();
// aparece la ventana emergente
_that.tools.setcss (_that.tools.getid ('gy_photobox'), {'visibilidad': 'visible'});
if (_that.tools.getid ('gy_photobox_firstload')) {
document.body.removechild (_that.tools.getid ('gy_photobox_firstload'));
}
// La función de devolución de llamada ejecutada cada vez que el conmutador está
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': 'Ninguno'});
}, 200);
eimg.src = 'gyphotobox/error.png';
etitle.innerhtml = 'no hay imágenes relacionadas';
_THAT.NIMGWIDTH = 400;
_THAT.NIMGHEight = 300;
_THAT.SetBOXCSS ();
_that.tools.setcss (_that.tools.getid ('gy_photobox'), {'visibilidad': 'visible'});
if (_that.tools.getid ('gy_photobox_firstload')) {
document.body.removechild (_that.tools.getid ('gy_photobox_firstload'));
}
}
});
},
btnprev: functer () {
var _that = this;
this.tools.getid ('gy_photobox_prev'). onClick = function () {
_THAT.NINDEX--;
_THAT.ImGChange ();
}
},
btnnext: functer () {
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) {
Caso 37: {
if (_that.nindex! = 0 && _ that.tools.getid ('gy_photobox_prev')) {
_THAT.NINDEX--;
_THAT.ImGChange ();
}
};romper;
Caso 39: {
if (_that.nindex! = (_that.nlen-1) && _ that.tools.getid ('gy_photobox_next')) {
_that.nindex ++;
_THAT.ImGChange ();
}
};romper;
Caso 27: {
_that.removeBox ();
};romper;
}
}
},
/*
@ dirección de imagen src [cadena]
@ Función de devolución de llamada @ Success [Función] para una carga de imagen exitosa
@ Error [función] función de devolución de llamada para la carga de imagen fallida
*/
Imgloading: function (opt) {
var _img = nueva imagen (),
_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 ();
}
}
// NOTA: debe colocarse debajo del evento Onload, de lo contrario, el IE tendrá un error
_img.src = opt.src;
},
FirstLoad: function (src, llamado) {
var _THAT = esto,
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 llamado == 'function') {
llamar de vuelta();
}
},
WindowResize: function () {
var _THAT = esto,
_Timer = null;
// Función de estrangulamiento
window.onresize = function () {
ClearTimeOut (_Timer);
_timer = setTimeOut (function () {
if (_that.tools.getid ('gy_photobox')) {
_THAT.SetBOXCSS ();
}
}, 100);
}
},
Herramientas: function () {
devolver{
getEvent: function (e) {
Return E || Window.event;
},
getTarget: function (e) {
regresar E.Target || E.Sracelement;
},
prevenDefault: function (e) {
E.PreventDefault? E.PreventDefault (): e.returnValue = false;
},
getId: function (id) {
return document.getElementById (id);
},
getCSS: function (nodo, valor) {
return node.CurrentStyle? node.CurrentStyle [valor]: getComputedStyle (nodo, nulo) [valor];
},
setCSS: function (nodo, val) {
para (var v en val) {
node.style.csstext += ';' +v +':' +val [v];
}
}
}
} ()
}
window.lgy_photobox = lgy_photobox;
}) ();
Representación final: