本文介绍一种通过JavaScript动态切换CSS类名来实现鼠标悬停时边框颜色变化的方法。相比直接查找替换样式,该方法通过定义overStyle和outStyle类,结合onmouseover和onmouseout事件,实现样式的复用与灵活控制,适用于需要动态交互的前端场景。
参考前一版本 https://www.jb51.net/article/33555.htm 可知,若需修改样式,可能依赖查找替换方式,灵活性不足。
为此,Insus.NET 提出另一种实现思路,旨在提升样式的复用性与应用广度。
定义CSS样式
首先定义所需的CSS样式:
代码如下:
<style type="text/css">
.overStyle
{
border-color:#3599ff;
}
.outStyle
{
border-color: #fff;
}
</style> JavaScript逻辑调整
同时调整JavaScript逻辑:
代码如下:
<script type="text/javascript">
function onOver(Id) {
Id.className = 'overStyle';
}
function onOut(Id) {
Id.className = 'outStyle';
}
</script> HTML动态应用
最后在HTML中应用动态效果:
代码如下:
<fieldset id="fs1" style="margin: 10px; padding: 10px; width: 170px; text-align: center;"
onmouseover="onOver(this)" onmouseout="onOut(this)">
ERP <a href="http://xxx.xxx.com/erp" target="_blank">http://xxx.xxx.com/erp </a>
</fieldset>