所以我正在做一个带有按钮的项目,当按钮被点击时,这些按钮会跟随命令。start是一个橙色的方框,我的命令可以让它变大、变蓝、变暗或重置。我想要添加一个“惊喜”按钮,用图片代替方框。
这是我在#button5的JS中的一个命令。我费了好大劲才把箱子搬开。
document.getElementById("button5").addEventListener(
"click",
function() {
document.getElementById("box").remove();
}
);<!-- <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> -->
<p>Press the buttons to change the box!</p>
<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div>
<button id="button1">Grow</button>
<button id="button2">Blue</button>
<button id="button3">Fade</button>
<button id="button4">Reset</button>
<button id="button5">Surprise</button>
发布于 2021-05-12 12:32:10
您可以使用此选项来切换图像:
document.getElementById("button5").addEventListener(
"click",
function(){
var box = document.getElementById("box");
if(box.style.display !== "none"){
document.getElementById("box").style.display = "none";
document.getElementById("image").style.display = "block";
return;
}
document.getElementById("box").style.display = "block";
document.getElementById("image").style.display = "none";
});<p>Press the buttons to change the box!</p>
<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px">
</div>
<img id="image" src="https://placekitten.com/150/150" style="display: none; height:150px; width:150px; margin:25px"></img>
<button id="button1">Grow</button>
<button id="button2">Blue</button>
<button id="button3">Fade</button>
<button id="button4">Reset</button>
<button id="button5">Surprise</button>
发布于 2021-05-12 12:32:10
不需要删除整个框,只需删除橙色,并创建一个新的img标记以在同一div标记中插入图像。
此外,每当单击任何其他按钮时,只需删除img标记即可。
已添加,单击两个按钮的事件以显示行为。
document.getElementById("button5").addEventListener("click", function () {
document.getElementById("box").style.backgroundColor = "";
let img = document.createElement("img");
img.setAttribute("src", ""); // add the image source here
img.setAttribute("id", "image");
img.setAttribute("alt", "image");
document.getElementById("box").append(img);
})
document.getElementById("button1").addEventListener("click", function () {
document.getElementById("box").style.backgroundColor = "orange";
document.getElementById("image").remove();
})<p>Press the buttons to change the box!</p>
<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div>
<button id="button1">Grow</button>
<button id="button2">Blue</button>
<button id="button3">Fade</button>
<button id="button4">Reset</button>
<button id="button5">Surprise</button>
发布于 2021-05-12 12:30:31
你可以在Javascript中通过innerHTML添加带有图像的超文本标记语言。
例如function addImage() { var newImage=document.getElementById('myBox'); newImage.innerHTML = '<img src="image.jpg" alt="image">'; console.log("add image"); }
https://stackoverflow.com/questions/67497327
复制相似问题