私はJavascriptでHTMLとCSSを学んでいます。私は現在、モーダルポップアップ機能のためにHTMLファイルからJavascriptコードを分離しようとしています。私はまだjqueryを学んでいないので、もしそれがなければこれを解決する方法があれば、それは大いに感謝されるでしょう。どのようにHTMLからモーダルのJavascriptを分離しますか?
完全なコードはここで見つけることができます:http://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img
HTMLコード:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="modal.css">
<script type="text/javascript" src="modal.js" ></script>
</head>
<body>
<h2>Image Modal</h2>
<img id="myImg" src="img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
</body>
</html>
外部JavaScriptコード:
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
上記の方法が動作しません。画像をクリックすると、モーダルポップアップは表示されません。私は単にスクリプトをリンクするだけでは不十分だと推測していますが、私はこの問題を解決するには十分に流暢ではありません。
はSOへようこそ。より良い答えを提供するには、これがなぜ問題を解決するのかを説明してください。 –
ブラウザのインポートでjsが同期しています。だから、あなたのjsファイルをインポートすると、あなたのdom htmlは(インスタンス化ではなく)domツリーで準備ができていません。 jsでdomオブジェクトを取得することはできません。 – paddy511
ありがとう、それは働いた。だから問題は、スクリプトを体に入れなければならないということでした。この場合、スクリプトが
で機能しないのはなぜですか? – Dobob