简体   繁体   中英

Change color when onmouseover

I want to change the color of a piece from image when onmouseover but not received:

My code:

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

What am I doing wrong?

Areas cannot have background colours; try this:

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

You can alternatively also use 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>

Try this code..

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>

Note that this.id will send the id of the element <area..> that is null in the code.. You need to send the string as the id of the map element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM