当前位置:首页 > JavaScript

js实现active

2026-02-01 14:32:08JavaScript

使用 JavaScript 实现 active 状态

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

js实现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}`);
  });
});

标签: jsactive
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

vue实现active

vue实现active

实现 Vue 中的 active 状态 在 Vue 中实现 active 状态通常用于高亮当前选中的元素,比如导航菜单、按钮或列表项。可以通过以下几种方式实现: 使用 v-bind:class 通过…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数: fun…