隐藏可见性,javascript?

时间:2013-06-05 12:09:20

标签: javascript visibility

有人可以告诉我为什么我的代码工作不正确,似乎无法弄清楚原因,这是一件非常简单的事情,所以我不明白为什么我找不到问题...

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

当我尝试显示大图时,我得到的消息是“无法读取未定义的属性'样式”。

4 个答案:

答案 0 :(得分:2)

你应该使用

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

答案 1 :(得分:1)

并非所有浏览器都支持

document.getElementsByClassName。您应该使用document.querySelectordocument.querySelectorAll,它几​​乎适用于所有浏览器,包括IE8 +。

答案 2 :(得分: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';

}

答案 3 :(得分:0)

尝试在img标签中添加样式属性,如下所示

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