[英]Scripts work inside HTML but not inside Scripts.js
最近我开始开发自己的网站并提高自己的编码知识。 有了这个,我已经开始遇到许多需要很长时间才能解决的问题,但到目前为止,除这个问题外,所有问题都已解决。
昨天我试图将 w3schools 中的“模态图像”添加到我创建的图片库中,除了脚本之外,一切似乎都在工作。
然后我决定将脚本隔离在一个完全独立的文件中,以确保代码确实有效并且不是我做错了什么。 一开始,当整个代码都卡在 HTML 中时,它确实起作用了,在我将 CSS 与 HTML 分开后,这没有引起任何问题,但是一旦我将脚本从 HTML 中取出到 Scripts.JS 中,模态就完全停止工作了.
由于我对 javascript 的了解几乎没有,我希望有人能对我的问题有所了解,因为我完全没有想法。
这是脚本。
PS:目前这是唯一一个不起作用的脚本,我还有其他脚本确实在同一个文件中工作,因此文件正在加载,只是这个特定的脚本无法正常工作。
// JavaScript Document
// 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.href ="";
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";
};
您的代码可能无法工作,因为它在 DOM 准备就绪之前正在运行。 尝试类似以下内容:
document.addEventListener("DOMContentLoaded", ready);
if (document.readyState === "interactive" || document.readyState === "complete" ) ready();
function ready(){
// 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.href ="";
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";
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.