You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否有jQuery相关方法可精简重复冗余的鼠标交互事件代码?

用户提问

[我的jQuery代码过长,具体如下]
示意图

$('.about').mouseenter(function(){
  $(this).css({'transform':'translateY(-32px)','transition':'0.5s','color':'rgb(202, 157, 117)'})})
    $('.about').mouseleave(function(
{$(this).css({'transform':'translateY(0px)','transition':'0.5s','color':'rgb(249, 240, 236)'})})

$('.progress').mouseenter(function(){
      $(this).css({'transform':'translateY(-32px)','transition':'0.5s','color':'rgb(202, 157, 117)'})})
        $('.progress').mouseleave(function(
    {$(this).css({'transform':'translateY(0px)','transition':'0.5s','color':'rgb(249, 240, 236)'})})

上述代码分别为.about、.progress类元素绑定了逻辑完全一致的鼠标移入、移出样式修改事件,存在大量重复内容,请问是否有jQuery相关方法可以精简这些冗余代码?

解决方案

可以通过jQuery内置特性大幅精简代码,以下是几种常用实现方案:

方案1:多选择器合并 + hover方法(最直接精简)

jQuery支持用逗号分隔同时选中多个目标元素,且内置hover()方法可一次性绑定鼠标移入、移出两个事件,不需要分开绑定。优化后代码如下:

// 同时选中所有需要绑定事件的元素
$('.about, .progress').hover(function() {
  // 鼠标移入逻辑
  $(this).css({
    'transform': 'translateY(-32px)',
    'transition': '0.5s',
    'color': 'rgb(202, 157, 117)'
  })
}, function() {
  // 鼠标移出逻辑
  $(this).css({
    'transform': 'translateY(0px)',
    'transition': '0.5s',
    'color': 'rgb(249, 240, 236)'
  })
})

注:原代码中$('.about').mouseleave(function(存在语法错误,缺少函数声明的右括号,优化时已修正。

方案2:样式配置抽离为变量(更易维护)

如果后续需要调整样式,直接修改公共变量即可,不需要改动事件逻辑:

// 抽离公共样式配置
const hoverStyle = {
  'transform': 'translateY(-32px)',
  'transition': '0.5s',
  'color': 'rgb(202, 157, 117)'
}
const normalStyle = {
  'transform': 'translateY(0px)',
  'transition': '0.5s',
  'color': 'rgb(249, 240, 236)'
}

$('.about, .progress').hover(function() {
  $(this).css(hoverStyle)
}, function() {
  $(this).css(normalStyle)
})

方案3:CSS类切换(推荐,结构样式分离)

更符合前端开发规范的实现是把样式规则写入CSS,jQuery仅负责类名切换,代码更简洁,性能也更好:
首先在CSS文件中定义样式:

.hover-effect {
  transition: 0.5s;
}
.hover-effect.active {
  transform: translateY(-32px);
  color: rgb(202, 157, 117);
}

给.about、.progress元素加上hover-effect类后,jQuery代码可简化为:

$('.about, .progress').hover(function() {
  $(this).addClass('active')
}, function() {
  $(this).removeClass('active')
})

内容的提问来源于stack exchange,提问作者SAIF RAO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:21:02