2 回答

TA貢獻1779條經驗 獲得超6個贊
是的,可以,有兩種方法可以做到這一點。
解決方案 A - HTML/JS 組合:
<!DOCTYPE html>
<html>
<body>
<img id="myImg"/>
<p>Click the button to change the value of the src attribute of the image.</p>
<p><b>Note:</b> The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
? document.getElementById("myImg").src = "hackanm.gif";
}
</script>
</body>
</html>
在這種方法中,您的 html 中有一個預定義的圖像標簽,但它沒有 img src。您可以在您想要的時間在 JavaScript 中進行設置 - 理想情況是當他們選擇方向或選項時。
所以在你的情況下它會是這樣的:
<p> Pick a direction to go </p>
<img id="myImg"/>
<input id = "input" type = "text" placeholder = "Type Help for actions"/><button onClick = "button()">Confirm</button>
<p id = "message"></p>
<script>
? function button() {
? ? var textInput;
? ? var newInput = input.value;
? ? if (newInput == "North") {
? ? ? textInput = "you went to the Abandoned Church";
? ? ? document.getElementById("message").innerHTML = textInput;
? ? ? document.getElementById("myImg").src = "church.png";
? ? }
? ? if (newInput == "North Again") {
? ? ? textInput = "you went to the Abandoned Someplace";
? ? ? document.getElementById("message").innerHTML = textInput;
? ? ? document.getElementById("myImg").src = "abandoned.png";
? ? }
? ? if (newInput == "Help") {
? ? ? textInput = "Commands you can use: <ul><li>South</li><li>North</li><li>East</li><li>West</li><li>North Again</li><li>South again</li><li>West Again</li><li>East Again</li><li>North One More</li><li>East Once More</li><li>West Once More</li><li>South Once More</li>";
? ? ? document.getElementById("message").innerHTML = textInput;
? ? }
? }
</script>
方案B——純JS:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to change the value of the src attribute of the image.</p>
<p><b>Note:</b> The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
? var img = document.createElement("img");
? img.id = "myImg";
? document.body.appendChild(img);
? document.getElementById("myImg").src = "hackanm.gif";
}
</script>
</body>
</html>
或者使用解決方案 B,您根本不需要<img/>在 html 中定義標簽,并且可以純粹從 javascript 創建它。

TA貢獻1810條經驗 獲得超4個贊
為此,如果采用數據驅動的方法會更好。如果您有一組可以查詢的數據,則可以檢索所需的任何內容,包括圖像 URL。這是您的用例的一個簡單示例:
let data = {
options: {
North: {
message: "you went to the Abandoned Church",
image: "https://picsum.photos/200/300?random=1"
},
South: {
message: "you went to the Abandoned Someplace",
image: "https://picsum.photos/200/300?random=2"
}
}
};
我還在這里為其創建了一個 Codepen:https ://codepen.io/richjava/pen/poJmKBg
我希望它有幫助。
- 2 回答
- 0 關注
- 145 瀏覽
添加回答
舉報