2013-06-05 38 views
0

有人可以告訴我爲什麼我的代碼不工作正確,似乎無法弄清楚爲什麼,這是一個非常簡單的事情,所以我不明白爲什麼我找不到問題...能見度隱藏,javascript?

var pictures = document.getElementById('contents').getElementsByClassName('pictureSmall'); 
    for(k=0; k<pictures.length; k++){ 
     pictures[k].onclick = showPic; 
     pictures[k].onblur = hidePic; 
    } 

function showPic(){ 
     var showPicture = this.getElementsByClassName('pictureBig')[0]; 
     showPicture.style.visibility = 'visible'; 

} 

function hidePic(){ 
     var showPicture = this.getElementsByClassName('pictureBig')[0]; 
     showPicture.style.visibility = 'hidden'; 

} 

這是HTML:

<div id="contents"> 
      <div class="pictureBig"><img src="bilder/boards.jpg" alt="cruisers"/></div> 
     <div id="main" class="content"> 

      <img src="bilder/miniboardm.jpg" alt="minicruiser" id="boardsprice"/> 
      <img src="bilder/miniboard2m.jpg" alt="minicruiser" id="boardgreen"/> 
      <img class="pictureSmall" src="bilder/boardssmall.jpg" alt="minicruisers" id="boardsmall"/> 
      <img class="pictureSmall" src="bilder/boardbluesmall.jpg" alt="shirt" id="small"/><div class="pictureBig"><img src="bilder/boards.jpg" alt="minicruisers"/></div> 
      <img class="pictureSmall" src="bilder/postersmall.jpg" alt="minicruiser" id="small2"/><div class="pictureBig"><img src="bilder/boards.jpg" alt="minicruisers"/></div> 
      <img src="bilder/boardcarving.jpg" alt="print" id="boardprint"/> 
      <p></p> 
     </div> 
</div> 

,這是CSS:

.pictureBig { 
    position:absolute; 
    display:none; 
    background-color:#EEE; 
    border:2px ridge #333; 
    padding:6px; 
    left:10px; 
    z-index:2; 
    margin-left:350px; 
} 

我得到的,當我嘗試顯示大畫面的消息是「無法讀取屬性「風格「未定義」。

+0

你能使用Chrome或Firefox調試器?使用Firefox,您可以安裝Firebug插件。按F12查看控制檯,它會顯示錯誤發生的行。在你的代碼中,你可以使用console.log(something);看看你的變量是否有預期的價值。 – HMR

+0

這意味着JavaScript無法弄清楚'this.getElementsByClassName('pictureBig')[0];' –

+0

你可以試試jQuery這麼簡單實現 –

回答

2

您應該使用

var showPicture = document.getElementsByClassName("pictureBig")[0]; 
+0

這個問題涉及Javascript範圍。 showPic函數中的'this'與單擊的pictureSmall元素相關,這顯然不會包含類名爲pictureBig的子元素。喬納森建議將'this'改爲'document'將解決這個問題。 –

1

document.getElementsByClassName在所有的瀏覽器不支持。您應該使用document.querySelectordocument.querySelectorAll,它幾乎可以在所有瀏覽器(包括IE8 +)中使用。

0

你可以試試這個:

function showPic(){ 
     var showPicture = this. 
      parentElement.parentElement.getElementsByClassName('pictureBig')[0]; 
     showPicture.style.visibility = 'visible'; 

} 

function hidePic(){ 
     var showPicture = this. 
      parentElement.parentElement.getElementsByClassName('pictureBig')[0]; 
     showPicture.style.visibility = 'hidden'; 

} 
0

嘗試添加的樣式屬性的img標籤,如下

<img src="bilder/miniboardm.jpg" alt="minicruiser" 
id="boardsprice" style="visibility:hidden"/>