当前位置:首页 > JavaScript

js实现 active

2026-03-14 01:31:33JavaScript

实现 active 状态的 JavaScript 方法

在 JavaScript 中,实现 active 状态通常涉及动态添加或移除 CSS 类,以改变元素的样式。以下是几种常见的方法:

使用 classList API

通过 classList.add()classList.remove() 方法可以方便地切换 active 类:

const element = document.querySelector('.target');
element.addEventListener('click', function() {
  this.classList.toggle('active');
});

直接修改 className 属性

对于较老浏览器兼容性,可以直接操作 className:

const btn = document.getElementById('button');
btn.onclick = function() {
  if (this.className.indexOf('active') === -1) {
    this.className += ' active';
  } else {
    this.className = this.className.replace('active', '');
  }
};

事件委托实现多个元素

当需要处理多个元素时,事件委托更高效:

document.addEventListener('click', function(e) {
  if (e.target.matches('.item')) {
    document.querySelectorAll('.item').forEach(el => {
      el.classList.remove('active');
    });
    e.target.classList.add('active');
  }
});

配合 CSS 过渡效果

添加平滑的视觉反馈:

.button {
  transition: background-color 0.3s ease;
}
.button.active {
  background-color: #4CAF50;
}

实际应用示例

导航菜单高亮

const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(item => {
  item.addEventListener('click', () => {
    navItems.forEach(i => i.classList.remove('active'));
    item.classList.add('active');
  });
});

表单输入框聚焦样式

js实现 active

const inputs = document.querySelectorAll('input');
inputs.forEach(input => {
  input.addEventListener('focus', () => {
    input.parentElement.classList.add('active');
  });
  input.addEventListener('blur', () => {
    input.parentElement.classList.remove('active');
  });
});

这些方法可以根据具体需求进行组合和调整,实现各种交互场景下的 active 状态效果。

标签: jsactive
分享给朋友:

相关文章

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js 实现倒计时

js 实现倒计时

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

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…