td 触发鼠标悬浮
时间: 2023-10-10 21:12:58 浏览: 68
在 HTML 中,可以使用 onmouseover 和 onmouseout 事件来触发鼠标悬浮效果。具体实现方法如下:
HTML 代码:
```html
<table>
<tr>
<td onmouseover="showText(this)" onmouseout="hideText(this)">单元格1</td>
<td onmouseover="showText(this)" onmouseout="hideText(this)">单元格2</td>
</tr>
<tr>
<td onmouseover="showText(this)" onmouseout="hideText(this)">单元格3</td>
<td onmouseover="showText(this)" onmouseout="hideText(this)">单元格4</td>
</tr>
</table>
```
JavaScript 代码:
```javascript
function showText(element) {
var text = element.innerHTML;
element.setAttribute('title', text);
}
function hideText(element) {
element.removeAttribute('title');
}
```
在这个例子中,我们在 td 标签上分别添加了 onmouseover 和 onmouseout 事件,当鼠标悬浮在单元格上时,会触发 showText 函数,将单元格中的文本赋值给 title 属性,从而实现悬浮显示文本的效果;当鼠标移开时,会触发 hideText 函数,将 title 属性移除,恢复原始状态。
可以注意到,我们在函数中使用了 this 关键字,它代表当前触发事件的元素,这样可以方便地获取对应的单元格元素和文本内容。