当前位置:首页 > JavaScript

js实现active

2026-02-01 14:32:08JavaScript

js实现active

使用 JavaScript 实现 active 状态

通过 JavaScript 动态添加或移除 active 类,可以高亮显示当前选中的元素。以下是几种常见实现方式:

通过事件监听器切换 active 状态

// 获取所有需要添加 active 状态的元素
const items = document.querySelectorAll('.item');

// 遍历元素并添加点击事件
items.forEach(item => {
  item.addEventListener('click', function() {
    // 移除其他元素的 active 类
    items.forEach(el => el.classList.remove('active'));
    // 为当前点击元素添加 active 类
    this.classList.add('active');
  });
});

通过事件委托优化性能

// 在父元素上监听点击事件
document.querySelector('.container').addEventListener('click', function(e) {
  // 检查点击目标是否是需要添加 active 的元素
  if (e.target.classList.contains('item')) {
    // 移除所有同类的 active 类
    document.querySelectorAll('.item').forEach(el => {
      el.classList.remove('active');
    });
    // 为点击目标添加 active 类
    e.target.classList.add('active');
  }
});

配合 CSS 实现视觉反馈

.item {
  /* 默认样式 */
  background-color: #fff;
  color: #333;
}

.item.active {
  /* 激活状态样式 */
  background-color: #007bff;
  color: white;
}

在单页应用(SPA)中保持 active 状态

// 根据当前路由设置 active 状态
function setActiveNav() {
  const currentPath = window.location.pathname;
  const navLinks = document.querySelectorAll('.nav-link');

  navLinks.forEach(link => {
    if (link.getAttribute('href') === currentPath) {
      link.classList.add('active');
    } else {
      link.classList.remove('active');
    }
  });
}

// 页面加载时执行
window.addEventListener('DOMContentLoaded', setActiveNav);
// 路由变化时执行
window.addEventListener('popstate', setActiveNav);

使用 dataset 存储状态信息

const buttons = document.querySelectorAll('[data-action]');

buttons.forEach(button => {
  button.addEventListener('click', function() {
    // 移除所有按钮的 active 状态
    document.querySelectorAll('[data-action]').forEach(btn => {
      btn.classList.remove('active');
    });
    // 设置当前按钮为 active
    this.classList.add('active');

    // 获取 data-action 值执行相应操作
    const action = this.dataset.action;
    console.log(`执行操作: ${action}`);
  });
});

js实现active

标签: jsactive
分享给朋友:

相关文章

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https:/…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Pa…