【1 var 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.Nonresize시 타이머 및 설정 타임 아웃을 정의하여 빈번한 통화가 발생하지 않도록합니다.
코드 사본은 다음과 같습니다.
windowresize : function () {
var _that = this,
_TIMER = NULL;
// 기능 스로틀링 기능
Window.onResize = function () {
클리어 타임 아웃 (_TIMER);
_timer = settimeout (function () {
if (_that.tools.getId ( 'gy_photobox')) {
_that.setboxcss ();
}
}, 100);
}
}
【3 load 그림 로딩 처리 기능
코드 사본은 다음과 같습니다.
/*
@ 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에 버그가 있습니다.
_img.src = opt.src;
}
소스 코드 :
코드 사본은 다음과 같습니다.
/*
저자 : Laoguoyong
*/
(기능(){
/* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@ 매개 변수 [String]
----------------------------------------------
★-다음 선택은 지원됩니다-★
@ 지원 첫 레벨 선택기 : '#ID', '. class', 'p'와 같은
@ '.class p', 'body span'과 같은 지원 자손 선택
@ '.class> p', 'body> span'과 같은 자식 요소 선택 지원
------------------------------------------
@ return [배열]
*/
var selector = function (str) {
// 요소 배열을 정의합니다
var elem = [];
/* 개인 방법
---------------------*/
// ID 인 요소를 반환합니다
함수 _getID (id) {
return document.getElementById (id);
}
//이 이름 요소로 요소를 반환합니다
함수 _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 <i; n ++) {
if (reg.test (node [n] .className)) {
class_array.push (노드 [n]);
}
}
return class_array;
}
// '#ID', 'p', '. class'와 같은 레벨 1 선택
// 반환 [배열]
함수 _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]);
}
}
반환 array_elem;
}
/*
@Arry_elm [array] : [ '.demo', 'p']와 같은 요소 배열, 아래의 p 요소를 선택하십시오. 후손 또는 후손을 선택할지 여부는 두 번째 매개 변수 설명을 참조하십시오.
@R [String] - 선택 사항 (기본값은 지나치지 않으면 후손을 선택하는 것입니다) : '>'는 후손을 선택하는 요소입니다.
---------------------------------------
@ return [array]
*/
함수 _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 (노드 [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 = child [i] .parentNode;
for (var n = 0; n <len; n ++) {
if (par.NodeType == 9) {
부서지다;
}
if (reg.test (par [type [0]]) {
elem.push (child [i]);
부서지다;
}또 다른{
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 <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));
}
}
귀환 엘렘;
}
/* 팝업 기능 생성자
------------------*//
함수 lgy_photobox (옵션) {
this.opt = 옵션;
this.otarget = typeof 옵션 .target == 'object'? 옵션 .target : selector (옵션 .target);
if (! this.otarget) 반환;
this.nlen = this.otarget.length; // 총 번호
this.abigimg_src = []; // 큰 이미지 데이터 배열
this.atitle = []; // 제목 데이터 배열
this.nindex = 0; //색인
this.nimgwidth = 0; // 이미지의 너비를 동적으로 가져옵니다
this.nimgheight = 0; // 이미지 높이를 동적으로 가져옵니다
이 .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),
대상 = _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 (type 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 () {
// 오버레이 생성
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'),
eboxPadding = 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);
// 이미지 크기가 보이는 범위를 초과합니다
if (this.nimgheight> hold_h) {
높이 = hold_h,
너비 = math.ceil (this.nimgwidth*(높이/this.nimgheight));
}
// 페이지 전체에 중앙에있는 상자를 설정합니다
this.tools.setcss (ebox, { 'width': width+'px',
'높이': ebox_head_h + height + 'px',
'마진-왼쪽':-( width+eboxpadding)/2+'px',
'상단': 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 = 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');
// 로딩 사진을 보여줍니다
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'), { '가시성': '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': _ th that.nindex, 'title': _ th that.atitle [_that.nindex]});
}
},
'오류': 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'), { '가시성': '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;
스위치 (e.keycode) {
사례 37 : {
if (_that.nindex! = 0 && _ that.tools.getid ( 'gy_photobox_prev')) {
_that.nindex-;
_that.imgchange ();
}
};부서지다;
사례 39 : {
if (_that.nindex! = (_that.nlen-1) && _ th that.tools.getid ( 'gy_photobox_next')) {
_that.nindex ++;
_that.imgchange ();
}
};부서지다;
사례 27 : {
_that.removebox ();
};부서지다;
}
}
},
/*
@ 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에 버그가 있습니다.
_img.src = opt.src;
},
첫 번째로드 : 기능 (SRC, 콜백) {
var _that = this,
html = document.createelement ( 'div');
html.id = 'gy_photobox_firstload';
document.body.appendChild (HTML);
this.tools.setcss (this.tools.getid ( 'gy_photobox_firstroad'), { 'top':( document.body.scrolltop || document.documentElement.scrolltop) +(document.documentElement.clientHeight/2) +'px'});
if (typeof callback == 'function') {
콜백 ();
}
},
windowresize : function () {
var _that = this,
_TIMER = NULL;
// 기능 스로틀링 기능
Window.onResize = function () {
클리어 타임 아웃 (_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;
},
PreverDefault : 함수 (e) {
e.preventDefault? e.preventDefault () : e.returnValue = false;
},
getid : function (id) {
return document.getElementById (id);
},
getcss : 함수 (노드, 값) {
return node.currentStyle? node.currentStyle [value] : getComputedStyle (Node, NULL) [value];
},
setcss : function (node, val) {
for (var in val) {
node.style.csstext += ';' +v +':' +val [v];
}
}
}
} ()
}
Window.lgy_photobox = lgy_photobox;
}) ();
최종 렌더링 :