我正在试着做硬币翻转网站。ı如何通过javascript或html将正面和反面转换为图像?
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};发布于 2020-08-30 06:38:20
创建一个html <img>元素:
<img id="coin" alt="coin"></img>然后像这样设置它的src:
function flip(coin) {
if(coin === "heads") {
document.getElementById("coin").src = "path/to/coin-heads.jpg";
} else if(coin === "tails") {
document.getElementById("coin").src = "path/to/coin-tails.jpg";
}
}发布于 2020-08-30 06:38:49
// Define heads and tails variables
var heads = '<headsPath>';
var tails = '<tailsPath>';
// Get the img element from the HTML file by its tag
var coin = document.getElementById('coin');
// Set the default displayed image to heads
coin.setAttribute('src', heads);
// When you click on the coin, run the function below
coin.addEventListener('click', function() {
// Get a random number
var randomNumber = Math.floor(Math.random() * 2);
// Log into the console the number given
console.log('The random number is: ' + randomNumber);
// If the number is 0, display heads, else display tails
if(randomNumber === 0) {
coin.setAttribute('src', heads);
} else {
coin.setAttribute('src', tails);
};
});<img id="coin">
发布于 2020-08-30 07:11:08
使用图像src并使用javascript进行更改。然后,您可以嵌入一个函数来检查条件,以查看当前设置了什么src,然后使用数组切换它们。我在图像本身上使用了一个点击事件监听器,不过也可以使用硬币来设置。
let imgsrc = ['https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg', 'https://static.toiimg.com/thumb/72975551.cms?width=680&height=512&imgsize=881753'];
let image = document.querySelector('.image');
image.addEventListener('click', function() {
if (image.src === imgsrc[0]) {
this.src = imgsrc[1];
} else if (image.src === imgsrc[1]) {
this.src = imgsrc[0];
}
})<img id="img" alt="" class="image" valign="center" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg" align="middle" border="0">
https://stackoverflow.com/questions/63652314
复制相似问题