在onmouseover时改变颜色

时间:2013-11-21 20:37:16

标签: javascript html5 javascript-events

我想在onmouseover但未收到时更改图像的颜色: 我的代码:

<img src="demo_usa.png" width="960" height="593" alt="Planets" usemap="#planetmap">
<map name="planetmap" id="map">
    <area id="myMap" shape="rect"  coords="0,0,120,126" alt="Sun" href="#" 
    onMouseOver="colorSwitch(this.id, '#ff9999');" />   
</map>

<script type="text/javascript">
function colorSwitch(id, color) {
    element = document.getElementById(id);
    element.style.background = color;
}
</script>

我做错了什么?

2 个答案:

答案 0 :(得分:0)

区域不能有背景颜色;试试这个:

<div id="planetmap">
    <img id="backgroundimage" src="demo_usa.png" width="960" height="593" alt="Planets"/>
    <div id="planet.1" class="planetmarker" style="left:0px;top:0px;width:120px;height:126px;">
    </div>
</div>

<style type="text/css">
    .planetmarker {
        position: absolute;
        z-index:1;
    }

    .planetmarker:hover {
        background-color: #ff9999;
    }
</style>

您也可以使用JavaScript:

<script type="text/javascript">
    function setOpacity(id, level) {
        element = document.getElementById(id);
        element.style.opacity = level;
    }
</script>
<style type="text/css">
    .planetmarker {
        position: absolute;
        z-index:1;
        background-color: #ff9999;
        opacity: 0;
    }
</style>
<div id="planetmap">
    <img id="backgroundimage" src="demo_usa.png" width="960" height="593" alt="Planets"/>
    <div id="planet.1" class="planetmarker" style="left:0px;top:0px;width:120px;height:126px;" onMouseOver="setOpacity(this.id, 1);" onMouseLeave="setOpacity(this.id, 0);">
    </div>
</div>

答案 1 :(得分:0)

试试这段代码..

<强> HTML:

<area shape="rect"  coords="0,0,120,126" alt="Sun" href="#"
  onMouseOver="colorSwitch('map', '#ff9999');" />  

<强>使用Javascript:

<script type="text/javascript">
function colorSwitch(id, color)
 {
   element = document.getElementById( id );
   element.style.background = color;
 }
</script>

请注意,this.id将在代码中发送元素为<area ..>的id。您需要将该字符串作为map元素的id发送