我在 Angular 2 中使用 Jquery 动态控制 svg 图像的 Css 样式。
1:使用鼠标悬停等事件进行控制
下面是一个简单的圆.svg图像的示例代码,其中定义了初始样式,并在圆圈上移动鼠标悬停事件,该事件将在悬停圆圈时触发"func1":
<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 更改的样式。它将看起来像这样:
func1(){
console.log("func1 has been called!");
$(".st0").css({"stroke":"yellow", "fill": "blue"});
}
尝试探索其他事件(例如"点击"(。
2. 通过表单输入进行控制
如果要使用表单输入更改 svg 的样式,则应使用动态绑定。模板中的附加代码(以及以前的 svg 代码(示例:
<form>
Stroke<input type="text" name="stroke" [(ngModel)]="stroke">
Fill<input type="text" name="fill" [(ngModel)]="fill">
<button (click)="submit()">Submit</button>
</form>
代码需要添加到相应的组件(.ts 文件(中:
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()"/>
尽量避免将jQuery与Angular2一起使用。