原生js高亮

67 阅读1分钟
Document *{margin: 0;padding: 0;} #box { width: 100%; height: 100%; overflow: hidden; box-sizing: border-box; } .itembox{ height: 50px; line-height: 50px; padding-left: 20px; box-sizing: border-box; } .active { background-color: yellow; }

````js`


    // 添加点击事件监听器
    boxElement.addEventListener('click', function(event) {
      // 获取点击的元素
      const clickedElement = event.target;
      if (clickedElement.classList.contains('itembox')) {
        // 获取当前激活的元素
        const activeElement = document.querySelector('.itembox.active');
        if (activeElement) {
          // 移除激活元素的 active 类
          activeElement.classList.remove('active');
        }
        // 添加点击元素的 active 类
        clickedElement.classList.add('active');
      }
    });
  });
</script>