在鼠标悬停时更改颜色

Change color when onmouseover

本文关键字:颜色 鼠标 悬停      更新时间:2023-09-26

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>

我做错了什么?

试试这个代码。。

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将发送代码中为null的元素<area ..>的id。。您需要将字符串作为map元素的id发送

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

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