如何更改元素的 CSS 类并在单击时删除所有其他类
Posted
技术标签:
【中文标题】如何更改元素的 CSS 类并在单击时删除所有其他类【英文标题】:How to change an element’s CSS class and remove all other classes on click 【发布时间】:2017-04-06 20:23:41 【问题描述】:如何在 AngularJS 2 中处理这样一种情况:单击一个元素时需要更改自己的样式,如果其他元素具有该样式,则需要将其删除——最好是在一个函数中。
类似于Angular.js How to change an elements css class on click and to remove all others,仅在 AngularJS 2 中,使用 TypeScript。
组件
https://plnkr.co/edit/Q2BoU4sNnXdaJB5vrZ8h?p=preview
//our root app component
import NgModule from '@angular/core'
import BrowserModule from '@angular/platform-browser'
import Component from '@angular/core';
@Component(
selector: 'my-app',
providers: [],
template: `
<div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="'my-class': isClassVisible ">
> I'm a div that gets styled on click
</div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="'my-class': isClassVisible ">
> I also want to be styled but only when Im clicked
</div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="'my-class': isClassVisible ">
> When one of us gets clicked the we want to be the only one with the style all others go back to normal
</div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="'my-class': isClassVisible ">
> I'm just here cause my creator likes even numbers
</div>
</div>
`,
styles: [
`
.my-class
background-color: yellow;
`
]
)
class App
isClassVisible: false;
constructor()
@NgModule(
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
)
export class AppModule
【问题讨论】:
一些使用Harrys answer plnkr.co/edit/z9PoHsPsc3k2dKzUH7zi?p=info的附加功能 【参考方案1】:解决问题的最简单方法是为每个包含的元素分配一个唯一 ID,同时使用另一个变量来保存选定的 ID。打开my-class
CSS 类的逻辑现在将基于选定的 ID。
您的新 html 模板:
<div (click)="toggleHighlight(1);" [ngClass]="'my-class': highlightedDiv === 1">
> I'm a div that gets styled on click
</div>
你的toggleHighlight
函数:
highlightedDiv: number;
toggleHighlight(newValue: number)
if (this.highlightedDiv === newValue)
this.highlightedDiv = 0;
else
this.highlightedDiv = newValue;
工作专线:https://plnkr.co/edit/fNoXWhUhMaUoeMihbGYd?p=preview
【讨论】:
并且使用类似的逻辑,我如何进行多项选择? @Timur 多选的工作方式与单选完全不同。您不能有一个通用规则来告诉何时关闭先前选择的元素(例如我应该在 x 或 y 选择之后关闭),或者当它满足第一个条件时关闭哪个元素(我应该关闭我选择的第一个,或者价值最低的那个等)【参考方案2】:在显示活动菜单方面对我有用的一个解决方案是在类中使用 typescript 变量名称,如
class=" text1Class "
并在打字稿中分配类名。
this.text1Class = "active";
或
this.text1Class = "inactive";
你需要像这样有不同的样式类
.inactive
background-color : gray;
padding : 10px;
.active
background-color : green;
padding : 10px;
在函数内部分配类名
textOneClicked() : void
this.text1Class = "active"; // set the active class
this.text2Class = this.text3Class = this.text4Class = "inactive"; // reset other classes
A working Plunker here
【讨论】:
【参考方案3】:我有一个解决这个问题的方法:
<div (click)="onclick($event);" >
> I'm a div that gets styled on click
</div>
应用程序:
class App
constructor()
onclick(event)
var l = event.target.parentElement.getElementsByClassName("my-class");
var count = l.length;
for(var i=0;i<count;i++)
l[i].className = "";
event.target.className = "my-class";
Plink: https://plnkr.co/edit/RHqL56GrTiV9olYE1Ars?p=preview
【讨论】:
不错的解决方案。我更喜欢它,因为它不会切换类。 其实也不是很好的解决办法。 Angular 的部分意义在于避免直接操作 DOM。【参考方案4】:Html code
<div [ngClass]="'first-div'">
<h2 [ngClass]="'heading'">Log In</h2>
<div [ngClass]="content">
<input type="text" placeholder="Enter User Name" name="username" id="username"#username class="in-cl">
<i class="fa fa-user fa-edited" aria-hidden="true"></i>
<input type="isPassword ? 'password':'text'" placeholder="Password" name="password" id="mypassword" #password class="in-cl">
<i class="fa fa-lock fa-lock-edited" aria-hidden="true" id="lock-id" (click)="onclick()"></i>
<button type="button" class="in-cl" (click)="credential(username.value,password.value)" >SIGN IN</button>
</div>
<div class="forgot">
<a href="#">Forgot Password?</a>
</div>
</div>
css代码
.first-div
width: 350px;
border: 2px solid black;
margin-left: auto;
margin-right: auto;
margin-top: 130px;
border-radius: 5px;
height: 400px;
background-color: black;
color: white;
.heading
color: white;
text-align: center;
font-weight: 500;
/* background-color: white; */
.in-cl
margin: 20px 20px 0px 20px;
border: 2px solid white;
border-radius: 15px;
height: 40px;
padding: 5px;
width: 300px;
outline: none;
color: black;
/* padding-right: 60px; */
::placeholder
color: black;
div button
background-color: #3aafa9;
color:black;
text-align: center;
border: none;
.forgot
margin: 15px;
text-align: center;
font-weight: 550;
color: white;
/* .image
position: absolute;
left: 825px;
top: 222px;
.lock-image
position: absolute;
left: 825px;
top: 282px;
*/
/* edited */
.fa-user:before
color: black;
.fa-lock:before
color: black;
.fa-unlock:before
color: black;
.fa-edited
top: 228px;
left: 770px;
position: absolute;
width: 28px;
.fa-lock-edited
top: 287px;
left: 772px;
position: absolute;
a
color: white;
ts 代码
import Component, OnInit from '@angular/core';
import Router from '@angular/router';
import swal from 'sweetalert2';
@Component(
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
)
export class LoginComponent
username:string="pavithra";
password:string="8792415337abcd";
p = document.getElementById('mypassword');
constructor(private router:Router)
credential(username:string,password:string)
if(this.username==username && this.password==password )
this.router.navigate(['/home'])
swal.fire(title:'Signed in successfully', confirmButtonColor:'#3aafa9', type:'success')
else
this.router.navigate(['/login'])
swal.fire(title:'Invalid Username or Password',type:'warning',position:'top-end')
isPassword = true;
onclick()
let body = document.getElementById('lock-id')
if (body.classList)
body.classList.toggle("fa-unlock");
this.isPassword = !(this.isPassword);
else
var classes = body.className.split(" ");
console.log(classes)
var i = classes.indexOf("fa-lock");
if (i >= 0)
classes.splice(i, 1);
else
classes.push("fa-unlock");
body.className = classes.join(" ");
【讨论】:
欢迎来到 ***。尝试更清楚地解释为什么这是问题的答案。以上是关于如何更改元素的 CSS 类并在单击时删除所有其他类的主要内容,如果未能解决你的问题,请参考以下文章