我正在构建一个用户正在吃冰淇淋的简单应用程序。每次用户单击按钮时,图像src都会更改为具有比另一图像少1个勺的图像。但是,如何多次更改图像的src?
var iceCream = document.getElementById("img");
var imgSrc;
function eat() {
var eating = document.getElementById("eat");
eating.play();
iceCream.src = imgSrc;
srcSelector()
}
function srcSelector() {
if ( iceCream.src === "images/5scoops.jpg") {
imgSrc = "4scoops.jpg";
}
}
img {
display: block;
margin-left: auto;
margin-right: auto;
}
button {
position: absolute;
left: 740px;
right: 400px;
top: 70%;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ice cream</title>
</head>
<body>
<img src="images/5scoops.jpg" id="img" alt="5 scoops ice cream">
<audio id="eat">
<source src="eat.mp3" type="audio/mpeg">
</audio>
<p>the button also plays an eating sound</p>
<button onclick="eat()">Eat!</button>
</body>
</html>
我从4个勺图像src确信,但是它不起作用(在我的原始页面中)。 我想做的:
答案 0 :(得分:0)
希望你不介意我用小猫代替冰淇淋,但你明白了:
var iceCream = document.getElementById("img");
var numberHint = document.getElementById("number");
var scoopsLeft = 5; // we start with 5 scoops left
function eat() {
if (scoopsLeft > 0) {
var eating = document.getElementById("eat");
eating.play();
scoopsLeft--; // reduce scoops left by one
iceCream.src = 'https://placekitten.com/200/200?image=' + scoopsLeft;
iceCream.alt = scoopsLeft + ' scoops ice cream left';
numberHint.innerHTML = iceCream.alt;
}
}
<img src="https://placekitten.com/200/200?image=5" id="img" alt="5 scoops ice cream left">
<audio id="eat">
<source src="http://soundbible.com/mp3/Cat%20Meow-SoundBible.com-1977450526.mp3" type="audio/mpeg">
</audio>
<p>the button also plays an eating sound</p>
<button onclick="eat()">Eat!</button>
<div id="number">5 scoops ice cream left</div>