0
我正在嘗試編寫一個腳本,它在鼠標懸停上更改圖像。我有6幅圖像,但該功能的工作只是其中的一個(第一個)JavaScript函數不適用於所有元素
<div id="picture-container">
<img class="picture" id="360" src="360.jpg" onclick="enlarge(360);" onmouseover="pic_info(360);"
onmouseout="pic_ret(360);"/>
<img class="picture" id="bmx" src="bmx.jpg" onclick="enlarge(bmx);"/>
<img class="picture" id="buzludzha" src="buzludzha.jpg" onclick="enlarge(buzludzha);"
onmouseover="pic_info(buzludzha);"/>
<img class="picture" id="pirata" src="pirata.jpg" onclick="enlarge(pirata);"
onmouseover="pic_info(pirata);"/>
<img class="picture" id="snowboard" src="snowboard.jpg" onclick="enlarge(snowboard);"
onmouseover="pic_info(snowboard);"/>
<img class="picture" id="vitiskali" src="vitiskali.jpg" onclick="enlarge(vitiskali);"
onmouseover="pic_info(vitiskali);"/>
<img class="picture" id="ispolin" src="ispolin.jpg" onclick="enlarge(ispolin);"
onmouseover="pic_info(ispolin);"/>
</div>
和腳本:正如我所說的腳本僅適用於用ID圖片
function pic_info(id) {
if (id == "360") {
var p = document.getElementById(id);
p.src = "360info.jpg";
}
if (id == "buzludzha") {
var p = document.getElementById(id);
p.src = "buzludzhainfo.jpg";
}
if (id == "pirata") {
var p = document.getElementById(id);
p.src = "piratainfo.jpg";
}
if (id == "snowboard") {
var p = document.getElementById(id);
p.src = "snowboardinfo.jpg";
}
if (id == "vitiskali") {
var p = document.getElementById(id);
p.src = "vitiskaliinfo.jpg";
}
if (id == "ispolin") {
var p = document.getElementById(id);
p.src = "ispolininfo.jpg";
}
= 「360」,它被導入到html文檔的head標籤中。同樣的事情發生在函數「enlarge();」中。爲什麼是這樣的,我該如何解決它? 謝謝,提前!
我可以建議你的代碼的重寫?一些東西沿着:'function pic_info(id){var p = document.getElementById(id); var src = id +「info.jpg」; p.src = src; },更容易閱讀和擴展到新功能。 – scragar 2014-09-22 12:03:10
不完全相關,但一個'var p = document.getElementById(id);'就足夠了,你不需要其中的六個... – Teemu 2014-09-22 12:03:11
刪除那些if語句...改用switch語句: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch – henser 2014-09-22 12:04:56