我正在尝试使用我的“outputImage”函数向图像包装器div“输出包装”添加和删除一个“屏幕上”类,该类使图像出现或消失。但是,当我在添加类之前 console.log 包含图像的元素(“输出包装”div)时,控制台指示该类已被分配!您可以从我的 HTML 中看到,“输出包装”div 在添加“屏幕”类之前没有任何类。这里发生了什么?
此外,如果图像已经具有“屏幕上”类,我想将其删除。但也会出现类似的现象。我通过 classList.remove() 删除了“on-screen”类,但是在删除后,“output-wrap”div 的 console.log 显示该类没有被删除。这是为什么?
function outputImage() {
// Get a random image
// let randomIndex = Math.round((Math.random() * (images.length - 1))),
// randomImageURL = images[randomIndex],
const randomImageURL = "https://picsum.photos/200/300";
image = document.getElementById("output-wrap"),
outputDiv = document.getElementById("output"),
output = `<img src="${randomImageURL}">`;
// If image already displayed
if (image.classList.contains("on-screen")) {
// Replace image
image.classList.remove("on-screen");
console.log(image) // Logs image with "on-screen" class...it should've been removed!
outputDiv.innerHTML = output;
// If no image is displayed
} else {
outputDiv.innerHTML = output;
console.log(image) // Logs image with "on-screen" class before class has been added!
image.classList.add("on-screen");
}
}
const button = document.querySelector("button");
button.addEventListener("click", outputImage);
body {
font-family: roboto;
background-color: rgb(78, 78, 78);
color: white;
}
#output-wrap {
position: absolute;
left: -450px;
transition: all 2s;
}
#output-wrap.on-screen {
animation: fadeIn ease 3s;
top: 200px;
transform: translateX(1200px);
}
img {
background-color: rgb(44, 44, 44);
width: 400px;
border-radius: 5%;
box-shadow: 10px 10px black;
}
<div class="breed-wrap">
<h1>Ultimate Dog Pic Viewer</h1>
<label for="breed">Breed</label>
<select name="breed" id="breed">
<option value="" disabled selected>--Select Breed--</option>
</select>
<button id="btn">Show me a picture!</button>
</div>
<div id="output-wrap">
<div id="output">Hello</div>
</div>
答案 0 :(得分:1)
您的代码没有问题。在添加 console.log
之后,此时只是 image
打印出了 on-screen
。当我刚刚发现时,这让我感到惊讶。
https://developer.mozilla.org/en-US/docs/Web/API/Console/log#logging_objects
在这种情况下执行 console.log 的正确方法是
console.log(JSON.parse(JSON.stringify(image, ['classList'])));