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

如何使用HostListener与指令实现<p>标签点击切换CSS类

修改方案

要实现点击<p>标签切换删除线样式的效果,直接修改指令代码即可,CSS和HTML部分保持不变:

保留原CSS

.strikethrough { text-decoration: line-through;}

保留原HTML

<p optionalIngredient>ABCD</p>

修改后的指令代码

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[optionalIngredient]'
})
export class OptionalIngredientDirective {
  // 新增状态变量,跟踪样式是否激活
  private isStrikethroughActive = false;

  constructor(private elRef: ElementRef, private renderer: Renderer2) { }

  // 替换为click事件监听
  @HostListener('click') onClick() {
    // 每次点击切换状态
    this.isStrikethroughActive = !this.isStrikethroughActive;
    
    if (this.isStrikethroughActive) {
      this.renderer.addClass(this.elRef.nativeElement, 'strikethrough');
    } else {
      this.renderer.removeClass(this.elRef.nativeElement, 'strikethrough');
    }
  }
}

关键改动说明

  • 新增isStrikethroughActive布尔变量,用来记录当前元素是否已经应用了删除线样式
  • 将原来的mouseenter和mouseleave事件监听替换为click事件,只需要一个点击处理方法
  • 在点击方法中,先切换状态值,再根据当前状态决定是添加还是移除CSS类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:27:26