`

Table的onMouseOver和onMouseOut鼠标事件的问题

阅读更多
看下面这段代码:

我们需要给某个TABLE加上鼠标事件的时候,一般希望当鼠标滑在整个TABLE之上的时候做某些处理,当鼠标滑出TABLE的时候做另外的处理. 一般情况下你会用onmouseover和onmouseout,代码如下:
<TABLE border="1" width=200 onmouseover="alert('鼠标滑进')" onmouseout="alert('鼠标滑出')">
    <TR>
        <TD id="TD1" noWrap height=25 onmouseenter="this.style.color='red'"> 菜单1</TD>
    </TR>
    <tr>
        <TD id="TD2" noWrap height=25 onmouseenter="this.style.color='red'"> 菜单2</TD>
    </TR>
    <TR>
        <TD id="TD3" noWrap height=25 onmouseenter="this.style.color='red'"> 菜单3</TD>
    </TR>
</TABLE>
按常理说:当鼠标进入table的时候就会弹出"鼠标滑进",当鼠标离开table的时候就会弹出"鼠标滑出"
但事实情况却是会不停地弹出"鼠标滑进""鼠标滑出",因为鼠标在TD之间滑动时也会触发TABLE的onmouseover和onmouseout事件。

如果是在IE下,则可以换用onmouseenter和onmouseleave来解决,示例代码如下:

<TABLE border="1" width=200 onmouseenter="alert('鼠标滑进')" onmouseleave="alert('鼠标滑出')">
    <TR>
        <TD id="TD1" noWrap height=25 onmouseenter="this.style.color='red'"> 菜单1</TD>
    </TR>
    <tr>
        <TD id="TD2" noWrap height=25 onmouseenter="this.style.color='red'"> 菜单2</TD>
    </TR>
    <TR>
        <TD id="TD3" noWrap height=25 onmouseenter="this.style.color='red'"> 菜单3</TD>
    </TR>
</TABLE>

如果是其他浏览器,则需要判断鼠标指针的坐标是否处于TABLE之外.示例代码如下(网上搜集):
<style type="text/css">...
html, body {...}{
padding:0px;
margin:0px;
}
</style><br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>

<table id="ta" width="350" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td bgcolor="#996633">&nbsp;</td>
    <td bgcolor="#234633"><button >  Clos</button></td>
    <td bgcolor="#0000FF">&nbsp;</td>
  </tr>
</table>
<script type="text/javascript">...
var rePosition = function (o) ...{
//获取元素绝对位置
var $x = $y = 0;
do ...{
$x += o.offsetLeft;
$y += o.offsetTop;
} while ((o = o.offsetParent) && o.tagName != "BODY");
return ...{ x : $x, y : $y };
};

window.onload = function () ...{
var wc = document.getElementById("ta"), ing = false;
wc.onmouseover = function () ...{
if (!ing) ...{
ing = true;
alert("over");
}
};

wc.onmouseout = function () ...{
var wc = this, e = window.event || e,
x = document.body.scrollLeft + e.clientX, y = document.body.scrollTop + e.clientY, p = rePosition(wc);
//alert(y);
if (x <= p.x || x >= (p.x + wc.offsetWidth) || y <= p.y || y >= (p.y + wc.offsetHeight)) ...{
alert("out");
ing = false;
}
};
};
</script>



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fishsoul/archive/2007/09/26/1801898.aspx
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics