我需要帮助,使用带有在文本框中输入的值或文本的开关箱来更改图像
您可以尝试这样的事情:
// Identifies urls and HTML elements
const
treeImage = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/Outeniqua_Yellowwood.JPG/199px-Outeniqua_Yellowwood.jpg",
dogImage = "https://3c1703fe8d.site.internapcdn.net/newman/csz/news/800/dingo.jpg",
imgElement = document.getElementById("imgElement"),
treeButton = document.getElementById("treeButton"),
dogButton = document.getElementById("dogButton");
// Adds a click listener that calls `maybeChangeImage` when user clicks something
document.addEventListener("click", maybeChangeImage);
// Defines a listener function (that automatically has access to the triggering event)
function maybeChangeImage(event){
const clickedThing = event.target; // The `target` property tells us what was clicked
// Ignores clicks that don't match our specification
if(!clickedThing.classList.contains("imageButton")){
return;
}
// Sets the `src` attribute of the `img` element depending on the clicked button's `id` attribute
else{ // `else` is technically unnecessary here because of `return` above
if(clickedThing.id === "treeButton"){
imgElement.src = treeImage;
}
else if(clickedThing.id === "dogButton"){
imgElement.src = dogImage;
}
}
}
imgElement{ width: 300px; }
<button id="treeButton" class="imageButton">Tree</button>
<button id="dogButton" class="imageButton">Dog</button>
<div>
<img id="imgElement" src="" />
</div>