2016-12-31 56 views
1

我正在使用HTML和Javascript進行個人投幣翻轉項目。有沒有辦法根據「翻轉」的結果來改變圖像。例如,如果它登陸它顯示了一個四分之一的側面和相同的尾巴?在HTML和JQuery中更改圖像

JavaScript代碼:

document.getElementById('click').onclick = click; 

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; 
}; 

HTML代碼:

<button id="click" type="button">CLICK ME</button> 
<p>You got: <span id="result"></span></p> 

回答

0

你,你只需要這個工作代碼...

var coins = { 
    heads: 'http://lorempixel.com/400/200/sports/heads is sports', 
    tails: 'http://lorempixel.com/400/200/animals/tails is animals', 
} 
document.getElementById("result").setAttribute('src', coins[coin]) 

document.getElementById('click').onclick = click; 
 

 
    var heads = 0; 
 
    var tails = 0; 
 
    var coins = { 
 
     heads: 'http://lorempixel.com/400/200/sports/heads is sports', 
 
     tails: 'http://lorempixel.com/400/200/animals/tails is animals', 
 
    } 
 
    function click() { 
 
     var result = Math.floor(Math.random() * 2) == 0 ? 'heads' : 'tails'; 
 
     flip(result) 
 
    }; 
 

 
    function flip(coin) { 
 
     document.getElementById("result").setAttribute('src', coins[coin]) 
 
    };
<button id="click" type="button">CLICK ME</button> 
 
    <p>You got: <img id="result" /></p>

+1

這似乎工作謝謝 – JakeMartin123

0

簡單地改變.src<img />
(你想要的link可以是任何東西,包括一個相對路徑,例如:"../../img/"

document.getElementById('click').onclick = click; 
 

 
var heads = 0; 
 
var tails = 0; 
 
function click() { 
 
    x = (Math.floor(Math.random() * 2) == 0); 
 
    if(x){ 
 
    flip("head"); 
 
    }else{ 
 
    flip("tail"); 
 
    } 
 
}; 
 
function flip(coin) { 
 
    var link = "http://www.marshu.com/articles/images-website/articles/presidents-on-coins/half-dollar-coin-"; 
 
    document.getElementById("result").src = link+coin+".jpg"; 
 
};
img {width:100px;}
<button id="click" type="button">CLICK ME</button> 
 
<p>You got: <img id="result" src="" /></p>