隐藏并显示带有更改图像的div

时间:2016-03-17 13:44:39

标签: javascript html css show-hide

我对Javascripthtml和所有这些事情都很陌生,我需要帮助改善我迄今所做的工作。

我正在尝试构建一个包含4个图像(充当按钮)和4个带数据的div的页面。所有4个div都设置为在启动时不显示。每个按钮用于一次显示一个div。那部分效果很好。

但是,当div设置为display : block时,我想要显示图像按钮的替代版本。

这是我到目前为止的javascript和html代码。

<script type = "text/javascript">
     var divState = {}
     function showHide(id) {
         if (document.getElementById) {
            var divid = document.getElementById(id);
            divState[id] = (divState[id]) ? false : true;

            for (var  div  in divState) {
               if (divState[div] && div !=id){
                   document.getElementById(div).style.display = 'none';
                   divState[div] = false ;
               }
            }
         divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
        }
     }
</script>

HTML:

<div id = "lob">
    <div id = "auto">
        <img src = "/intact/formindem/SiteAssets/LOB/Jeep_v2.png" alt = "Experts auto";
            onmouseover = "this.src = '/intact/formindem/SiteAssets/LOB/Auto_TXT.png'";
            onmouseout = "this.src = '/intact/formindem/SiteAssets/LOB/Jeep_v2.png'";
            onclick = "showHide('MSOZoneCell_WebPartWPQ3')";
            width = 175px; />
    </div>

<div id = "habitation">
        <img src = "/intact/formindem/SiteAssets/LOB/House_v4.png" alt = "Experts habitation";
            onmouseover = "this.src = '/intact/formindem/SiteAssets/LOB/Habit_txt.png'";
            onmouseout = "this.src = '/intact/formindem/SiteAssets/LOB/House_v4.png'";
            onclick = "showHide('MSOZoneCell_WebPartWPQ4')";
            width = 175px; />
    </div>

    <div id = "route">
        <img src = "/intact/formindem/SiteAssets/LOB/Road_v1.png" alt = "Experts route";
            onmouseover = "this.src = '/intact/formindem/SiteAssets/LOB/Route_TXT.png'";
            onmouseout = "this.src = '/intact/formindem/SiteAssets/LOB/Road_v1.png'";
            onclick = "showHide('MSOZoneCell_WebPartWPQ5')";
            width = 175px; />
    </div>

    <div id = "tous">
        <img src = "/intact/formindem/SiteAssets/LOB/All.png" alt = "Tous les experts";
            onmouseover = "this.src = '/intact/formindem/SiteAssets/LOB/Tous_TXT.png'";
            onmouseout = "this.src = '/intact/formindem/SiteAssets/LOB/All.png'";
            onclick = "showHide('MSOZoneCell_WebPartWPQ6')";
            width = 175px; />
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

弗雷德,

我看到你在这里尝试做什么。您是否考虑过使用CSS代替JavaScript?这是CSS的目的,虽然JS可以做到,但它会更复杂(而且速度更慢,在较慢的移动浏览器上可能会很明显)。

类似的东西:

#route {
    background-image: url("your-image-here.png");
    background-size: contain;
}

#route:hover {
    background-image: url("your-mouseover-image-here.png");
}

另外,对我来说,当容器设置为display: block时,您希望以不同方式显示某些内容,这似乎很奇怪。你想用它做什么?可能有更好的解决方案可以达到这种效果。