我正在研究這個博客,它有一個列出所有帖子的頁面。因此,我為每個帖子添加了自定義懸停和活動樣式,因此當懸停時,它會根據每個帖子顯示不同的顏色和框陰影強度。
假設 Post1 有一個與之關聯的紅色,那么它的默認 box-shadow 顏色將為紅色,其模糊為 10px。但是當懸停或單擊時,它的框陰影也將是紅色的,但模糊將是 30px 以聚焦它正在懸停/單擊。
現在對于 Post2,如果關聯的顏色是藍色,那么它將具有默認和懸停/活動框陰影顏色為藍色,模糊將分別為 10 像素和 30 像素。
當在帖子外或另一個帖子上單擊時,當前帖子上的活動框陰影將恢復為默認值(10px)。這是我現在無法實作的。當前帖子上的活動陰影不會消失。
這是組件:
@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回傳的陣列僅包含一個已被選中的帖子。如果未選中,則回傳空。
uj5u.com熱心網友回復:
嘗試將 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476167.html
上一篇:MinIO學習
