javascript - 单击 Angular 组件外部后无法删除事件框阴影

标签 javascript angular

我正在创建这个博客,其中有一个页面列出了所有帖子。因此,我为每个帖子添加了自定义悬停和事件样式,因此当悬停时,它将根据每个帖子显示不同的颜色和框阴影强度。

假设 Post1 具有与之关联的红色,因此它的默认框阴影颜色将为红色,其模糊将为 10px。但是当悬停或单击时,它的框阴影也将是红色的,但模糊将为 30px,以集中显示它正在悬停/单击。

现在,对于 Post2,如果关联的颜色为蓝色,那么它将具有默认和悬停/事件框阴影颜色为蓝色,模糊将分别为 10px 和 30px。

当在帖子外部或另一个帖子上单击时,当前帖子上的事件框阴影将恢复为默认值(10 像素)。而这正是我现在所无法实现的。当前帖子上的事件阴影不会消失。

这是组件:

@Component({
  selector: 'post',
  templateUrl: './post.component.html', 
  styleUrls: ['./post.component.scss']
})
class Post {
  hoverPostId: number;
  clickedPostId: number;

  constructor() {}

  defaultStyle( color ) {
    const boxShadow = `1px 10px 1px ${color}`;    

    return {
      'box-shadow': boxShadow
    };
  }

  hoverActiveStyle( color ) {
    const boxShadow = `1px 30px 1px ${color}`;    

    return {
      'box-shadow': boxShadow
    };
  }

  postActive( postId: number ) {

    if ( this.post.id === postId ) {
      this.clickedPostId = postId;
    } else {
      this.clickedPostId = null;
    }

  }

  mouseEnter( postId: number ) {
    this.hoverPostId = postId;
  }

  mouseLeave() {
    this.hoverPostId = null;
  }

}

export default Post;

这是模板:

<div 
  class="post" 
  [ngStyle]="hoverPostId === post.id || clickedPostId === post.id ? hoverActiveStyle(post.color) : defaultStyle(post.color)"
  (mouseenter)="mouseEnter(post.id)"
  (mouseleave)="mouseLeave()"
  (click)="postActive(post.id)"
>

   // post content
  
</div>

请注意,我无法在 scss 文件中对悬停和事件类的样式进行硬编码,因为每个帖子的颜色都是唯一的。所以请不要建议这样做。

======更新========

还值得一提的是,在我的帖子组件中,我可以访问所选的帖子。像 this.posts.selected 这样的东西会返回一个仅包含一篇已选择的帖子的数组。如果未选择,则返回空。

最佳答案

尝试将 tabindex 属性添加到 div

<div 
  tabindex="0"
  class="post" 
  [ngStyle]="hoverPostId === post.id || clickedPostId === post.id ? hoverActiveStyle(post.color) : defaultStyle(post.color)"
  (mouseenter)="mouseEnter(post.id)"
  (mouseleave)="mouseLeave()"
  (click)="postActive(post.id)"
  (blur)="onBlur()"
>

   // post content
  
</div>

如果你在 *ngFor 中有这个,你可以使用迭代的索引

  [tabindex]="i"

当元素失去焦点时,(blur) 事件会触发。通过 tabindex 设置焦点。

  onBlur() {
    this.clickedPostId = null;
    // Or do your thing here
  }

关于javascript - 单击 Angular 组件外部后无法删除事件框阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72255930/

相关文章:

javascript - 不显示特定通知 React Native

angular - 无法在 typescript 上设置 sweetalert 选项

javascript - ngx-quill/quill.js 从innerHTML中去除自定义印迹

angular - 使用 ng2-smart-table 编辑和创建

Angular 4.4.6 延迟加载模块中的共享服务

javascript - 从对象中获取实体的最佳方法是什么?

javascript - 正则表达式:从这个到那个匹配,除非另一个字符位于中间

javascript - URL 以谷歌在 Chrome 中的方式编码字符串

javascript - 在 Angular 中链接可观察订阅的最佳方式?

javascript - 从 JavaScript 连接到 Oracle DB