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 关注
- 108 浏览
添加回答
举报