【1】 Используйте 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,
ширина = this.nimgwidth,
высота = this.nimgheight;
[2] Оптимизация событий DOM, когда Window.Onresize определите таймер и установленное время, чтобы предотвратить частые вызовы
Кода -копия выглядит следующим образом:
windowresize: function () {
var _that = это,
_timer = null;
// Функция дросселя
window.onresize = function () {
ClearTimeOut (_Timer);
_timer = setTimeout (function () {
if (_that.tools.getid ('gy_photobox')) {
_that.setboxcss ();
}
}, 100);
}
}
【Три】 Функция обработки загрузки изображения
Кода -копия выглядит следующим образом:
/*
@ src [string] Адрес изображения
@ успех [функция] Функция обратного вызова для успешной загрузки изображения
@ error [function] Функция обратного вызова для неудачной загрузки изображения
*/
imgloging: function (opt) {
var _img = новое изображение (),
_That = это;
_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 будет иметь ошибку
_img.src = opt.src;
}
исходный код:
Кода -копия выглядит следующим образом:
/*
Автор: Лаогуйон
*/
(function () {
/* ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@ Параметры [строка]
---------------------------------------
★-только следующие выборы поддерживаются-★
@ Поддержка селекторов первого уровня: например, '#id', '. Class', 'p'
@ Поддержка потомка, например, '.class p', 'Span'
@ Поддержка выбора детских элементов, например, '.class> p', 'body> span'
----------------------------------------
@ return [массив]
*/
var selecter = function (str) {
// Определите массив элементов
var elem = [];
/* Частный метод
---------------------*//
// возвратный элемент, который есть идентификатор
функция _getid (id) {
return document.getElementbyId (id);
}
// возвращать элемент с помощью этого элемента
функция _getbyclassname (classname, parent) {
var class_array = [],
node = parent! = undefined && parent.nodetype == 1? Parent.getElementsBytagNam
reg = new Regexp ("(^| // s)"+classname+"(// s | $)");
for (var n = 0, i = node.length; n <i; n ++) {
if (reg.test (node [n] .classname)) {
class_array.push (node [n]);
}
}
return class_array;
}
// Выбор 1 -го уровня, такой как «#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 (ы);
for (var n = 0, i = tag.length; n <i; n ++) {
array_elem.push (Tag [n]);
}
}
return array_elem;
}
/*
@Arry_elm [Array]: массив элементов, такой как ['.demo', 'p'], выберите элемент p ниже .demo. Что касается того, следует ли выбрать потомков или потомков, см. Второй объяснение параметра
@R [String] - необязательно (по умолчанию выбирать потомков, если вы не пройдете): '>', является элементом выбора потомков;
------------------------------------
@ return [массив]
*/
функция _query (array_elem, r) {
var node = array_elem,
type_name = node [0] .match (//#/)?
child = _getdom (узел [1]),
type = type_name.split ('_'),
len = document.getelementsbytagname ('*'). Длина,
reg = new Regexp ("(^| // s)"+type [1]+"(// s | $)") ;;
for (var i = 0, j = child.length; i <j; i ++) {
var par = kild [i] .parentnode;
for (var n = 0; n <len; n ++) {
if (par.nodeType == 9) {
перерыв;
}
if (reg.test (par [type [0]])) {
elem.push (ребенок [i]);
перерыв;
}еще{
if (r == '>') break;
par = par.parentnode;
}
}
}
}
/* Интерфейс
----------------------*/
varemstr = str.replace (/(^/s+) | (/s+$)/, '');
if (document.queryselectorall) {
var dom = document.queryselectorall (elemstr);
для (var n = 0, len = dom.length; n <len; n ++) {
elem.push (dom [n]);
}
}еще{
var split = /^/sí/g.exec(elemstr);
if (split) {
var node = elemstr.split (split [0]);
_query (узел, разделить [0]);
}еще{
elem = elem.concat (_getdom (elemstr));
}
}
вернуть Элем;
}
/* Конструктор всплывающей функции
----------------------*/
function lgy_photobox (option) {
this.opt = опция;
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.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);
// На странице просмотра настройки нет панели прокрутки.
_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 ();
// Стоп прыжок
вернуть ложь;
}
}
},
CreateBoxdom: function () {
var doc = документ,
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>'+
'/'+ это.nlen+
'</span>'+
'<p id = "gy_photobox_title"> </p>'+
'</div>'+
'</div>';
},
CreateCover: function () {
// Создать наложение
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: function () {
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'),
eBoboDpadding = 10,
hold_h = nwindow_h - eboxpadding - 50 - ebox_head_h,
ширина = this.nimgwidth,
высота = this.nimgheight;
// alert ('nwindow_h:'+nwindow_h+'-'+'eboxpadding:'+eboxpadding+'-'+'ebox_head_h:'+ebox_head_h);
// Размер изображения превышает видимый диапазон, Zoom
if (this.nimgheight> hold_h) {
высота = hold_h,
width = math.ceil (this.nimgwidth*(height/this.nimgheight));
}
// Установите центр коробки на всей странице
this.tools.setcss (ebox, {'width': width+'px',
«высота»: ebox_head_h + height + 'px',
'Margin-Lefft' :-( Ширина+eBoboSpadding)/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 = документ;
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 <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 (название);
}
},
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 = это,
_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');
// Показать картинку загрузки
this.tools.setcss (eloadingtips, {'display': 'block'});
this.tools.setcss (einfor, {'display': 'none'});
// судить левые и правые кнопки для отображения
this.btnisshow ();
// обработка загрузки изображения
this.imgloading ({
'src': _ src,
'успех': 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') {
>
}
},
'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.tools.getid ('gy_photobox_prev'). onclick = function () {
_that.nindex--;
_that.imgchange ();
}
},
btnnext: function () {
var _that = это;
this.tools.getid ('gy_photobox_next'). onclick = function () {
_that.nindex ++;
_that.imgchange ();
}
},
KeyEvent: function () {
var _that = это;
document.onkeydown = function (e) {
var e = e || window.event;
Switch (e.keycode) {
Случай 37: {
if (_that.nindex! = 0 && _ that.tools.getid ('gy_photobox_prev')) {
_that.nindex--;
_that.imgchange ();
}
};перерыв;
Случай 39: {
if (_that.nindex! = (_That.nlen-1) && _ that.tools.getid ('gy_photobox_next')) {
_that.nindex ++;
_that.imgchange ();
}
};перерыв;
Случай 27: {
_that.removebox ();
};перерыв;
}
}
},
/*
@ src [string] Адрес изображения
@ успех [функция] Функция обратного вызова для успешной загрузки изображения
@ error [function] Функция обратного вызова для неудачной загрузки изображения
*/
imgloging: function (opt) {
var _img = новое изображение (),
_That = это;
_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 будет иметь ошибку
_img.src = opt.src;
},
первая загрузка: function (src, обратный вызов) {
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 (typeOf обратный вызов == 'function') {
перезвонить();
}
},
windowresize: function () {
var _that = это,
_timer = null;
// Функция дросселя
window.onresize = function () {
ClearTimeOut (_Timer);
_timer = setTimeout (function () {
if (_that.tools.getid ('gy_photobox')) {
_that.setboxcss ();
}
}, 100);
}
},
Инструменты: function () {
возвращаться{
getEvent: function (e) {
возврат E || window.event;
},
getTarget: function (e) {
вернуть E.Target || E.srcelement;
},
Предотвратить: 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 [значение]: getComputEdStyle (Node, NULL) [значение];
},
setCss: function (node, val) {
для (var v in val) {
node.style.csstext += ';' +v +':' +val [v];
}
}
}
} ()
}
window.lgy_photobox = lgy_photobox;
}) ();
Окончательный рендеринг: