検索
ホームページウェブフロントエンドjsチュートリアルネイティブJavaScriptで画像ポップアップインタラクティブ効果を実現_JavaScriptスキル

【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,
width = this.nImgWidth ,
高さ = this.nImgHeight

【2】Domイベントの最適化、window.onresize時にイベントの頻繁な呼び出しを防ぐタイマーsetTimeoutを定義

コードをコピーします コードは次のとおりです:
windowResize:function(){
var _that = this,
_timer = null;
// 関数のスロットリング
window.onresize = function(){
「 _timer = setTimeout(function(){
If( _that.tools.getId('gy_photoBox')){
_that.setBoxCss();
}

},100);                                                                              }




【3】画像読み込み処理機能


コードをコピー コードは次のとおりです:

/*
@ src [文字列] 画像のアドレス
@success[Function] 画像読み込み成功時のコールバック関数
@ error [関数] 画像読み込み失敗時のコールバック関数
*/
imgLoading:function(opt){
var _img = 新しい画像(),
_that = this;
_img.onload = function(){
_that.nImgWidth = this.width;
_that.nImgHeight = this.height;
If(typeof opt.success == '関数'){
setTimeout(function(){
opt.success();
},300);
}
}
_img.onerror = function(){
If(opt.error の種類){
opt.error();
                                                                                      }
// 注: onload イベントの下に配置する必要があります。そうしないと BUG が ie
に表示されます。 _img.src = opt.src;
}

ソースコード:

コードをコピー コードは次のとおりです:

/*
著者:laoguoyong
*/
(関数(){
/* ------------------------単純なセレクタ--------------- --- -
@パラメータ [文字列]
--------------------------------------
★-次のオプションのみがサポートされています-★
@ 第 1 レベルのセレクターをサポートします: '#id'、'.class'、'p'
など @ '.class p'、'body scan' などの子孫の選択をサポートします
@ '.class>p'、'body>span'
などのサブ要素の選択をサポートします。 --------------------------------------
@ return [配列]
*/
var セレクター = function(str){
//要素配列を定義
var elem = [];
/* プライベート メソッド
------------------------*/
//id
を持つ要素を返します 関数 _getId(id){
return document.getElementById(id);
}
//そのような名前を持つ要素を返します - 要素
function _getByClassName(className,parent){
var class_array = [],
ノード = 親 != 未定義&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
reg = new RegExp("(^|\s)" className "(\s|$)");
for(var n=0,i=node.length;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)));
}
else{
var tag = document.getElementsByTagName(s);
for(var n=0,i=tag.length;n array_elem.push(tag[n]);
}
}
return array_elem;
}
/*
@arry_elm [配列]: ['.demo','p'] のような要素配列、.demo 配下の p 要素が選択されます。子孫を選択するか子孫を選択するかについては、第 2 パラメータを参照してください。説明
@ r [文字列] - オプション (渡されない場合、デフォルトでは子孫が選択されます): '>'、子孫要素を選択します。        ------------------------
        @ return [配列]
        */
        function _query(array_elem,r){
            var ノード = array_elem,
                type_name = ノード[0].match(/#/)?'id_' ノード[0].slice(1):node[0].match(/./)?'className_' ノード[0].slice(1) ):'tagName_' ノード[0]、
                子 = _getDom(node[1]),
                type = type_name.split('_'),
                len = document.getElementsByTagName('*').length,
                reg = new RegExp("(^|\s)" type[1] "(\s|$)");;
            for(var i=0,j=child.length;i                 var par = child[i].parentNode;
                for(var n=0;n                     if(par.nodeType == 9){
                        休憩;
                    }
                    if(reg.test(par[type[0]])){
                        elem.push(child[i]);
                        壊す;                   
                    }その他{
                        if(r == '>') ブレーク;
                        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                 elem.push(dom[n]);
            }
        }その他{
            var split = /[>s]/g.exec(elemStr);
            if(分割){
                var ノード = elemStr.split(split[0]);
                _query(node,split[0]);
            }その他{
                elem = elem.concat( _getDom(elemStr) );
            }
}
return elem;
}
/* ポップアップ ウィンドウ関数コンストラクター
-----------------------*/
関数LGY_photoBox(オプション){
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;
This.getData();
for(var n=0;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();
                    //阻止跳转
                    return 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 = '
'+
                            '
'+
                            ''+
                            '
'+exHtml+'
'+
                            '
'+
                                'ネイティブJavaScriptで画像ポップアップインタラクティブ効果を実現_JavaScriptスキルhttp://www.pconline.com.cn/blank.gif" />'+
                                'ネイティブJavaScriptで画像ポップアップインタラクティブ効果を実現_JavaScriptスキル'+
                                '
'+
                                    ''+
                                        ''+
                                        '/'+this.nLen+
                                    '
'+
                                    '

'+
                                '
'+
                            '
';
        }、
        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,
                width = this.nImgWidth ,
                高さ = this.nImgHeight;
            //alert('nWindow_h:' nWindow_h '-' 'eBoxPadding:' eBoxPadding '-' 'eBox_head_h:' eBox_head_h);
            // 图片大小超过可范围、放放実行
            if(this.nImgHeight>hold_h){
                高さ =hold_h,
                width = Math.ceil(this.nImgWidth*(height/this.nImgHeight));
            }
            //設置盒子在整页面居中
            this.tools.setCss(eBox,{'width':width 'px',
                                    'height':eBox_head_h 高さ 'px',
                                    'margin-left':-(width 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'});
            //設置覆盖層の样式
            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                 var src = this.oTarget[n].getAttribute('href'),
                    title = this.oTarget[n].getAttribute('title');
                this.aBigimg_src.push(src);
                if(!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 == '関数'){
_that.opt.onChange({'src':_src,'index':_that.nIndex,'title':_that.aTitle[_that.nIndex]});
                                                                                                                                                                             },
'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;
This.tools.getId('gy_photoBox_prev').onclick = function(){
                _that.nインデックス--;
                _that.imgChange();
            }
        }、
        btnNext:function(){
            var _that = this;
            this.tools.getId('gy_photoBox_next').onclick = function(){
                _that.nインデックス ;
                _that.imgChange();
            }
        }、
        keyEvent:function(){
            var _that = this;
            document.onkeydown = function(e){
                変数 e = e || window.event;
                switch(e.keyCode){
                    ケース 37:{
                        if(_that.nIndex != 0&&_that.tools.getId('gy_photoBox_prev')){
                            _that.nインデックス--;
                            _that.imgChange();   
                        }
                    };ブレイク;
                    ケース 39 :{
                        if(_that.nIndex != (_that.nLen-1)&&_that.tools.getId('gy_photoBox_next')){
                            _that.nインデックス ;
                            _that.imgChange();   
                        }
                    };ブレイク;
                    ケース 27:{
                        _that.removeBox();                           
                    };ブレイク;
                }
            }
        }、
        /*
        @ src [文字列] 画像の地址
        @ success [関数] 画像追加成功の回调関数
        @ error [関数] 画像追加ダウンロード失敗の回调関数
        */
        imgLoading:function(opt){
            var _img = 新しい画像(),
                _あれ = これ;
            _img.onload = function(){
                _that.nImgWidth = this.width;
                _that.nImgHeight = this.height;
                if(typeof opt.success == '関数'){
                    setTimeout(function(){
                        opt.success();
                    },300);
                }
            }
            _img.onerror = function(){
                if(opt.error の種類){
                    opt.error();
                }
            }
            // 注意:要放在onloadイベント下面,否则ie会出现BUG
            _img.src = opt.src;
        }、
        firstLoad:function(src,callback){
            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(コールバックの種類 == '関数') {
                コールバック();
            }
        }、
        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){
                    || を返しますwindow.event;
                }、
                getTarget:function(e){
                    e.target を返す || e.srcElement;
                }、
                PreventDefault: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){
                    for(var v in val){
                        ノード.スタイル.cssText = ';' v ':' val[v];
                    }
                }
            }
        }()
    }
    window.LGY_photoBox = LGY_photoBox;
})();

最終终效果图:

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
JavaScript:Web言語の汎用性の調査JavaScript:Web言語の汎用性の調査Apr 11, 2025 am 12:01 AM

JavaScriptは、現代のWeb開発のコア言語であり、その多様性と柔軟性に広く使用されています。 1)フロントエンド開発:DOM操作と最新のフレームワーク(React、Vue.JS、Angularなど)を通じて、動的なWebページとシングルページアプリケーションを構築します。 2)サーバー側の開発:node.jsは、非ブロッキングI/Oモデルを使用して、高い並行性とリアルタイムアプリケーションを処理します。 3)モバイルおよびデスクトップアプリケーション開発:クロスプラットフォーム開発は、反応および電子を通じて実現され、開発効率を向上させます。

JavaScriptの進化:現在の傾向と将来の見通しJavaScriptの進化:現在の傾向と将来の見通しApr 10, 2025 am 09:33 AM

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

javascriptの分解:それが何をするのか、なぜそれが重要なのかjavascriptの分解:それが何をするのか、なぜそれが重要なのかApr 09, 2025 am 12:07 AM

JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

pythonまたはjavascriptの方がいいですか?pythonまたはjavascriptの方がいいですか?Apr 06, 2025 am 12:14 AM

Pythonはデータサイエンスや機械学習により適していますが、JavaScriptはフロントエンドとフルスタックの開発により適しています。 1. Pythonは、簡潔な構文とリッチライブラリエコシステムで知られており、データ分析とWeb開発に適しています。 2。JavaScriptは、フロントエンド開発の中核です。 node.jsはサーバー側のプログラミングをサポートしており、フルスタック開発に適しています。

JavaScriptをインストールするにはどうすればよいですか?JavaScriptをインストールするにはどうすればよいですか?Apr 05, 2025 am 12:16 AM

JavaScriptは、最新のブラウザにすでに組み込まれているため、インストールを必要としません。開始するには、テキストエディターとブラウザのみが必要です。 1)ブラウザ環境では、タグを介してHTMLファイルを埋め込んで実行します。 2)node.js環境では、node.jsをダウンロードしてインストールした後、コマンドラインを介してJavaScriptファイルを実行します。

クォーツでタスクが開始される前に通知を送信する方法は?クォーツでタスクが開始される前に通知を送信する方法は?Apr 04, 2025 pm 09:24 PM

Quartzタイマーを使用してタスクをスケジュールする場合、Quartzでタスク通知を事前に送信する方法、タスクの実行時間はCron式によって設定されます。今...

JavaScriptでは、コンストラクターのプロトタイプチェーンで関数のパラメーターを取得する方法は?JavaScriptでは、コンストラクターのプロトタイプチェーンで関数のパラメーターを取得する方法は?Apr 04, 2025 pm 09:21 PM

JavaScriptプログラミング、プロトタイプチェーンの関数パラメーターの理解と操作のJavaScriptのプロトタイプチェーンの関数のパラメーターを取得する方法は、一般的で重要なタスクです...

WeChat MiniプログラムWebViewでVUE.JSダイナミックスタイルの変位が失敗した理由は何ですか?WeChat MiniプログラムWebViewでVUE.JSダイナミックスタイルの変位が失敗した理由は何ですか?Apr 04, 2025 pm 09:18 PM

WeChatアプレットWeb-ViewでVue.jsを使用する動的スタイルの変位障害がvue.jsを使用している理由の分析...

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境