jsの勉強でコンストラクタ関数を使ってモーダルライブラリを作成しているのですが、
制作につまづいているのでアドバイスをいただけますでしょうか。
機能の詳細
- 第一引数にtargetにイベントを発火させたい要素のID、第二引数のcontentにモーダルで表示したい要素のIDを指定
- targetのクリックでイベントが発火。overlayとデリートボタン、contentのwrapper要素を生成
- contentの要素は横幅と高さを取得し、画面中央に表示させる
- deleteボタンとoverlayクリック時にモーダル非表示
困っていること
- イベントを発火させる記述の方法
(Modal.prototype.showContentとModal.prototype.hideContentの部分)
備考
- contentにimg要素などを入れた場合に、画面中央表示させることはできました。
- headタグ内に書かれているscriptは最終的には外部ファイルとして読み込み、html側は最小限の記述で済むようにしたいです。(インスタンスの生成のみ)
<!DOCTYPE html> <html lang="ja"> <head> <link rel="stylesheet" href="index.css"> <meta charset="UTF-8"> <title>サンプル</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script> function Modal(target, content) { this.target = $(target); this.content = $(content); this.width = this.getContentWidth(); this.height = this.getContentHeight(); this.content.css({ zIndex: '999', position: 'absolute', top: '50%', left: '50%', display: 'none', marginTop: '-' + this.height / 2 + 'px', marginLeft: '-' + this.width / 2 + 'px', }); } Modal.prototype.getContentWidth = function() { var width = this.content.width(); return width; } Modal.prototype.getContentHeight = function() { var height = this.content.height(); return height; } Modal.prototype.showContent = function() { this.target.after('<div id="js-overlay" class="overlay"></div>'); this.target.after('<div id="js-button" class="button-delete"></div>'); this.content.wrap('<div class="content-wrapper"></div>'); this.content.css({ display: 'block', }); } Modal.prototype.hideContent = function() { this.target.after(''); this.target.after(''); this.content.wrap(''); this.content.css({ display: 'none', }); } </script> </head> <body> <div class="button-container"> <div id="button-left" class="button"> <p>サンプルボタンA</p> </div> <div id="content-left"> </div> <div id="button-center" class="button"> <p>サンプルボタンB</p> </div> <div id="content-center"> </div> <div id="button-right" class="button"> <p>サンプルボタンC</p> </div> <div id="content-right"> </div> </div> <script> var modalLeft = new Modal('#button-left', '#content-left'); var modalCenter = new Modal('#button-center', '#content-center'); var modalRight = new Modal('#button-right', '#content-right'); </script> </body> </html>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。