Angular 2:通过UI上的用户输入/事件动态控制SVG图像/图标Css样式 [英] Angular 2 : Controlling SVG Image/Icon Css Styles dynamically through user inputs/events on UI
问题描述
我使用Jquery在Angular 2中动态控制svg图像的Css样式。
I used Jquery to control the Css styles of svg image dynamically in Angular 2.
1:使用鼠标悬停等事件进行控制
下面是一个简单圆圈.svg图像的示例代码,其中定义了初始样式,并且圆圈上的鼠标悬停事件将在悬停圆圈时触发'func1':
Below is a sample code for a simple circle .svg image with initial styles defined and a mouseover event on circle which will trigger 'func1' on hovering the circle:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 175.7 177" style="enable-background:new 0 0 175.7 177;" xml:space="preserve">
<style type="text/css">
.st0{
fill:#FFFFFF;
stroke:#000000;
stroke-width:4;
stroke-miterlimit:10;
}
</style>
<circle id="XMLID_1_" class="st0" cx="91.2" cy="87.2" r="10" (mouseover)="func1()"/>
现在定义此函数:func1()在其对应的组件(.ts文件)中使用您的样式想要使用jquery进行更改。它看起来像这样:
Now define this function: func1() in its corresponding component (.ts file) with the styles you want to be changed using jquery. It will look like this:
func1(){
console.log("func1 has been called!");
$(".st0").css({"stroke":"yellow", "fill": "blue"});
}
尝试探索其他事件(如点击)。
Try to explore other events also (like 'click').
2。通过表单输入进行控制
如果要使用表单输入更改svg的样式,则应使用动态绑定。
模板中的其他代码示例(以及之前的svg代码):
If you want to change styles of svg using form inputs you should use dynamic binding. Sample additional code (along with previous svg code) in template:
<form>
Stroke<input type="text" name="stroke" [(ngModel)]="stroke">
Fill<input type="text" name="fill" [(ngModel)]="fill">
<button (click)="submit()">Submit</button>
</form>
代码需要添加到相应的组件(.ts文件)中:
Code need to be added in corresponding component (.ts file):
stroke:any;
fill:any;
submit(){
console.log("submit called!"+ this.stroke+" and "+ this.fill);
$(".st0").css({"stroke":this.stroke, "fill": this.fill});
}
推荐答案
只需使用 ngStyle
指令
<circle [ngStyle]="{stroke:stroke, fill: fill}"
id="XMLID_1_"
class="st0" cx="91.2" cy="87.2" r="10"
(mouseover)="func1()"/>
只需使用 ngStyle
指令
<circle [style.stroke]="stroke"
[style.fill]="fill"
id="XMLID_1_"
class="st0" cx="91.2" cy="87.2" r="10"
(mouseover)="func1()"/>
尽量避免在Angular2中使用jQuery。
Try to avoid using jQuery with Angular2.
这篇关于Angular 2:通过UI上的用户输入/事件动态控制SVG图像/图标Css样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!