【1】 Utilisez VAR pour déclarer plusieurs variables, ce qui est beaucoup plus rapide que d'utiliser VAR pour chaque variable
La copie de code est la suivante:
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,
largeur = this.nimgwidth,
hauteur = this.nimgheight;
[2] Optimisation de l'événement DOM, lorsque Window.Nesize, définissez une minuterie et settimeout pour empêcher les appels fréquents de se produire
La copie de code est la suivante:
windowResize: function () {
var _That = ceci,
_timer = null;
// Fonctionnement de la fonction
window.onresize = function () {
ClearTimeout (_timer);
_timer = setTimeout (function () {
if (_that.tools.getID ('gy_photobox')) {
_That.setBoxcss ();
}
}, 100);
}
}
【Trois】 Fonction de traitement de chargement d'image
La copie de code est la suivante:
/ *
Adresse d'image @ src [String]
@ Success [fonction] Fonction de rappel pour le chargement d'image réussi
Fonction de rappel d'erreur [fonction] pour le chargement d'image échoué
* /
imgloading: function (opt) {
var _img = nouvelle 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 ();
}
}
// Remarque: il doit être placé sous l'événement Onload, sinon l'IE aura un bogue
_img.src = opt.src;
}
Code source:
La copie de code est la suivante:
/ *
Auteur: Laoguoyong
* /
(fonction(){
/ * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@ Paramètres [String]
---------------------------------------
★ -Un les sélections suivantes sont prises en charge - ★
@ Prise en charge des sélecteurs de premier niveau: tels que «#id», «classe», «p»
@ Soutien des descendants, tels que «.class p», «Body Span»
@ Soutenez la sélection des éléments enfants, tels que '.class> p', 'body> span'
----------------------------------------
@ return [array]
* /
var sélecteur = fonction (str) {
// définir un éventail d'éléments
var elem = [];
/ * Méthode privée
--------------------- * /
// Élément de retour qui est ID
fonction _getID (id) {
return document.getElementById (id);
}
// Renvoie l'élément avec cet élément de nom
fonction _GetByClassName (className, parent) {
var class_array = [],
Node = parent! = Undefined && parent.NodeType == 1? Parent.getElementsByTagName ('*'): document.getElementsByTagName ('*'),
reg = new regexp ("(^ | // s)" + classname + "(// s | $)");
pour (var n = 0, i = node.length; n <i; n ++) {
if (reg.test (node [n] .classname)) {
class_array.push (nœud [n]);
}
}
return class_array;
}
// Sélection de niveau 1, comme «#id», «p», «classe»
// retourne [Array]
fonction _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)));
}
autre{
var tag = document.getElementsByTagName (s);
pour (var n = 0, i = tag.length; n <i; n ++) {
array_elem.push (tag [n]);
}
}
return array_elem;
}
/ *
@arry_elm [array]: le tableau des éléments, tel que ['.demo', 'p'], sélectionnez l'élément p ci-dessous .demo. Quant à choisir des descendants ou des descendants, veuillez consulter l'explication du deuxième paramètre
@r [String] - Facultatif (par défaut est de sélectionner les descendants si vous ne passez pas): '>', est l'élément de sélection des descendants;
------------------------------------
@ return [array]
* /
fonction _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 (nœud [1]),
type = type_name.split ('_'),
len = document.getElementsByTagName ('*'). Longueur,
reg = new regexp ("(^ | // s)" + type [1] + "(// s | $)") ;;
pour (var i = 0, j = child.length; i <j; i ++) {
var par = enfant [i] .parentNode;
pour (var n = 0; n <len; n ++) {
if (par.NodeType == 9) {
casser;
}
if (reg.test (par [type [0]])) {
elem.push (enfant [i]);
casser;
}autre{
if (r == '>') Break;
par = par.parentNode;
}
}
}
}
/ * Interface
---------------------- * /
var elemstr = str.replace (/ (^ / s +) | (/ s + $) /, '');
if (document.queryselectorall) {
var Dom = document.QuerySelectorAll (elemstr);
pour (var n = 0, len = dom.length; n <len; n ++) {
elem.push (dom [n]);
}
}autre{
var Split = / ■//s
if (Split) {
var node = elemstr.split (Split [0]);
_Query (nœud, Split [0]);
}autre{
elem = elem.concat (_getdom (elemstr));
}
}
retour elem;
}
/ * Constructeur de fonction pop-up
---------------------- * /
fonction lgy_photobox (option) {
this.opt = option;
this.otarget = typeof option.target == 'objet'? option.target: sélecteur (option.target);
if (! this.otarget) retourner;
this.nlen = this.otarget.length; // Nombre total
this.abigimg_src = []; // grand tableau de données d'image
this.atitle = []; // Titre Data Array
this.Nindex = 0; //Indice
this.nimgWidth = 0; // Obtenez dynamiquement la largeur de l'image
this.nimgheight = 0; // Obtenez dynamiquement la hauteur de l'image
this.ndelay = 0,2;
this.intit ();
}
Lgy_photobox.prototype = {
intit: function () {
var _That = this;
this.getData ();
pour (var n = 0; n <this.nlen; n ++) {
this.otarget [n] .index = n;
this.otarget [n] .onclick = fonction (e) {
_That.CreateCover ();
var e = _that.tools.getEvent (e),
Target = _That.tools.getTTarget (E);
// Aucune barre de défilement n'apparaît sur la page de navigation des paramètres
_That.tools.setcss (document.DocumentElement, {'Height': '100%', 'Overflow-y': 'Hidden', 'Overflow-x': 'Hidden'});
// Obtenez l'index à ce moment-là
_That.Nindex = this.index;
// Premier jugement
_That.Firstload (_That.abigimg_src [_That.Nindex], fonction () {
// insérer une structure
_That.CreateBoxdom ();
//fermeture
_That.tools.getID ('gy_photobox_close'). onclick = function () {
_That.RemoveBox ();
}
// juge les boutons gauche et droit à afficher
_That.BtNissHow ();
// Précédent
_That.btnprev ();
// Suivant
_That.Btnnext ();
// Chargez l'image
_That.imgChange (_That.abigimg_src [_That.Nindex]);
});
// Réinitialiser la taille de la fenêtre
_That.WindowResize ();
// Événements de clavier
_That.KeyEvent ();
// Arrête de sauter
retourne 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 = '<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_loking" 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>' +
'/'+tTis.nlen+
'</span>' +
'<p id = "gy_photobox_title"> </p>' +
'</div>' +
'</div>';
},
createCover: function () {
// Créer une superposition
var doc = document,
coverhtml = doc.createElement ('div');
coverhtml.id = 'gy_photobox_cover';
doc.body.ApendChild (CoverHtml);
// Définit le style du calque de superposition
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,
largeur = this.nimgwidth,
hauteur = this.nimgheight;
// alert ('nwindow_h:' + nwindow_h + '-' + 'eboxpadding:' + eboxpadding + '-' + 'ebox_head_h:' + ebox_head_h);
// La taille de l'image dépasse la plage visible, zoom
if (this.nimgheight> hold_h) {
height = hold_h,
width = math.ceil (this.nimgwidth * (hauteur / this.nimgheight));
}
// Définit la boîte centrée sur toute la page
this.tools.setcss (ebox, {'width': width + 'px',
'hauteur': ebox_head_h + height + 'px',
'margin-left' :-( largeur + 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'});
// Définit le style du calque de superposition
this.tools.setcss (this.tools.getID ('gy_photobox_cover'), {'height': nscrolltop + doc.documentElement.clientHeight + 'px'});
},
supprimebox: 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 () {
pour (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 (titre);
}
},
btnisshow: function () {
this.tools.setcss (this.tools.getID ('gy_photobox_prev'), {'affiche': 'block'});
this.tools.setcss (this.tools.getID ('gy_photobox_next'), {'affiche': 'block'});
if (this.nindex == 0) this.tools.setcss (this.tools.getID ('gy_photobox_prev'), {'affiche': 'non'});
if (this.nindex == (this.nlen-1)) this.tools.setcss (this.tools.getID ('gy_photobox_next'), {'affiche': 'non'});
},
imgchange: function () {
var _That = ceci,
_src = this.abigimg_src [this.nindex],
eloadingtips = this.tools.getID ('gy_photobox_img_loking'),
eimg = this.tools.getID ('gy_photobox_img'),
etitle = this.tools.getID ('gy_photobox_title'),
einfor = this.tools.getID ('gy_photobox_infor');
// montre une image de chargement
this.tools.setcss (eloadingtips, {'affiche': 'block'});
this.tools.setcsss (einfor, {'affiche': 'Aucun'});
// juge les boutons gauche et droit à afficher
this.btnisshow ();
// Traitement de chargement d'image
this.imgloading ({
'src': _ src,
'Success': function () {
_That.tools.setcsss (eloadingtips, {'affiche': 'Aucun'});
_That.tools.setcsss (einfor, {'affiche': 'block'});
// Définit le vrai chemin d'image, le titre, le numéro de page actuel
eimg.src = _src;
etitle.innerhtml = _That.atitle [_That.Nindex];
_That.tools.getID ('gy_photobox_index'). innerHtml = (_That.Nindex + 1);
// Set Style
_That.setBoxcss ();
// fenêtre pop-up apparaît
_That.tools.setcss (_that.tools.getID ('gy_photobox'), {'visibilité': 'visible'});
if (_that.tools.getID ('gy_photobox_firstload')) {
document.body.removechild (_that.tools.getID ('gy_photobox_firstload'));
}
// La fonction de rappel exécutée chaque fois que le commutateur 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.setcsss (eloadingtips, {'affiche': 'Aucun'});
}, 200);
eimg.src = 'gyphotobox / error.png';
etitle.innerhtml = «pas de photos liées»;
_That.nimgWidth = 400;
_That.NIMGHEIGHT = 300;
_That.setBoxcss ();
_That.tools.setcss (_that.tools.getID ('gy_photobox'), {'visibilité': '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 = fonction (e) {
var e = e || window.event;
commutateur (e.KeyCode) {
cas 37: {
if (_That.Nindex! = 0 && _ that.tools.getID ('gy_photobox_prev')) {
_That.Nindex--;
_That.imgChange ();
}
};casser;
cas 39: {
if (_That.Nindex! = (_That.nlen-1) && _ that.tools.getID ('gy_photobox_next')) {
_That.Nindex ++;
_That.imgChange ();
}
};casser;
Cas 27: {
_That.RemoveBox ();
};casser;
}
}
},
/ *
Adresse d'image @ src [String]
@ Success [fonction] Fonction de rappel pour le chargement d'image réussi
Fonction de rappel d'erreur [fonction] pour le chargement d'image échoué
* /
imgloading: function (opt) {
var _img = nouvelle 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 ();
}
}
// Remarque: il doit être placé sous l'événement Onload, sinon l'IE aura un bogue
_img.src = opt.src;
},
Firstload: fonction (src, rappel) {
var _That = ceci,
html = document.CreateElement ('div');
html.id = 'gy_photobox_firstload';
Document.Body.ApendChild (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 = ceci,
_timer = null;
// Fonctionnement de la fonction
window.onresize = function () {
ClearTimeout (_timer);
_timer = setTimeout (function () {
if (_that.tools.getID ('gy_photobox')) {
_That.setBoxcss ();
}
}, 100);
}
},
Outils: fonction () {
retourner{
getEvent: fonction (e) {
retourner e || window.event;
},
getTarget: function (e) {
return e.target || e.srcelement;
},
PARVERDEFAULT: FONCTION (E) {
E.PreventDefault? E.PreventDefault (): e.reTurnValue = false;
},
getID: fonction (id) {
return document.getElementById (id);
},
getcss: fonction (noeud, valeur) {
return node.currentStyle? node.currentStyle [valeur]: getCompuledStyle (node, null) [valeur];
},
setcss: fonction (noeud, val) {
pour (var v dans val) {
node.style.csstext + = ';' + v + ':' + val [v];
}
}
}
} ()
}
window.lgy_photobox = lgy_photobox;
}) ();
Rendu final: