二话不说,先上gif图:

绑定点击事件 (click)="事件名()"
绑定src="{{变量名}}"
DOM元素获取:ViewChild, ElementRef, AfterViewInit;
ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素。视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在 ngAfterViewInit 钩子函数中,才能正确获取查询的元素。
一、通过img的src实现图片颜色切换
- 绑定src :src="{{pngUrl}}"
- 奇偶次切换,原理类似toggle
<ul>
<li>
//添加按钮点击事件pngChange
<button type="button" name="button" (click)="pngChange()">蓝色png,点击变成绿色</button>
<img width="40" alt="Angular Logo" src="{{pngUrl}}" #png class="png">
</li>
</ul>
//DOM元素获取的话需要import ViewChild, ElementRef, AfterViewInit;
import { Component,ViewChild,ElementRef, AfterViewInit } from '@angular/core';
export class AppComponent {
@ViewChild('png') png:ElementRef; //获取到该元素
public pngUrl = "../assets/blue.png"; //定义src的绑定变量
public count1 = 0; //用以判断点击的奇偶次
//点击改变png图片颜色,奇数绿色,偶数蓝色,类似toggle
pngChange(){
this.count1 ++;
if(this.count1 %2 ==1) {
console.log(11);
this.pngUrl="../assets/green.png";
}else {
this.pngUrl="../assets/blue.png";
}
}
//必须要写的
ngAfterViewInit() {
// console.log(222);
}
}
二、<svg>直接嵌在html页面中
<ul>
<li>
<button type="button" name="button" (click)="svgChange()">粉色svg,点击点击变成橙色</button>
//path是矢量路径,这个有专门的svg编辑器生成这些代码,不用管~
<svg viewBox="0 0 1024 1024" width="40" height="40" class="svg" #svg>
<path d="M768 728.615385v-7.876923-11.815385c-11.815385-110.276923-122.092308-196.923077-256-196.923077s-244.184615 86.646154-256 192.984615v23.63077c0 43.323077 35.446154 78.769231 78.769231 78.76923h354.461538c43.323077 0 78.769231-35.446154 78.769231-78.76923zM512 1024C228.430769 1024 0 795.569231 0 512S228.430769 0 512 0s512 228.430769 512 512-228.430769 512-512 512z m0-555.323077c94.523077 0 169.353846-74.830769 169.353846-169.353846S606.523077 126.030769 512 126.030769s-169.353846 78.769231-169.353846 173.292308 74.830769 169.353846 169.353846 169.353846z" #path fill="#d4237a"></path>
</svg>
</li>
</ul>
//导包
import { Component,ViewChild,ElementRef, AfterViewInit } from '@angular/core';
//元素获取 svg或者这个path它俩任意一个都能改变颜色,就是在事件触发时找到nodeValue会有点差别~
@ViewChild('svg') svg:ElementRef;
@ViewChild('path') path:ElementRef;
//用以判断奇偶次
public count2 = 0;
//事件触发
svgChange(){
this.count2++;
if(this.count2 % 2== 1) {
//针对svg的元素进行变色属性获取操作,一般选这种方案,
this.svg.nativeElement.firstChild.attributes[2].nodeValue="orange";
//这是对<path>标签的DOM获取后的颜色操作
// this.path.nativeElement.farthestViewportElement.firstChild.attributes.fill.nodeValue="orange";
} else {
this.svg.nativeElement.firstChild.attributes[2].nodeValue="#d4237a";
// this.path.nativeElement.farthestViewportElement.firstChild.attributes.fill.nodeValue="#d4237a";
}
}
-
svg的属性列表
svg

-
path的属性列表
this.path.nativeElement.farthestViewportElement.firstChild.attributes.fill.nodeValue="你想要的颜色值"
其实都大同小异,获取DOM以后console一下,控制台里找一找,基本上关于属性的改变大都记录在attributes这一个关键key中~~
大爱svg,因为是矢量图,一直保持清晰。咱们常用到的iconfont字体图标,就是svg~svg不仅可以直接通过img的src引入,也可以把<svg>整个标签复制到html页面中也没有问题~
网友评论