如何将模式的Javascript与html分离



我正在用Javascript学习HTML和CSS。我目前正在尝试将Javascript代码与html文件分离,以实现模式弹出功能。我还没有学习jquery,所以如果有一种方法可以在没有它的情况下解决这个问题,我将不胜感激。

完整的代码可以在这里找到: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";
}

以上方法不起作用。当我点击图片时,没有模式弹出。我猜仅仅链接脚本是不够的,但我的语言不够流利,无法解决这个问题。

您可以将脚本标记放入body中。如下所示。

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="modal.css">
</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>
    <script src="your url"></script>
</body>
</html>

您不需要以任何形式链接它。嵌入js就足够了。但是你犯了一个错误。页面从上到下进行解析。javascript在html完全加载之前运行。因此,像getElementById这样的东西不起作用,因为该元素当时不存在。要在加载页面时运行代码,请执行以下操作js:

window.onload=function(){
//do awesome stuff
yourelement=document.getElementById("yourelement");
}

最新更新