jquery - Angular 2 : Controlling SVG Image/Icon Css Styles dynamically through user inputs/events on UI

标签 jquery html css angular svg

我在 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()"/>

现在在其对应的组件(.ts 文件)中定义此函数:func1(),其中包含您要使用 jquery 更改的样式。它看起来像这样:

func1(){
   console.log("func1 has been called!");
   $(".st0").css({"stroke":"yellow", "fill": "blue"});
}

也尝试探索其他事件(例如“点击”)。

<强>2。通过表单输入进行控制

如果您想使用表单输入更改 svg 的样式,您应该使用动态绑定(bind)。 模板中的示例附加代码(以及之前的 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()"/>

尽量避免在 Angular2 中使用 jQuery。

关于jquery - Angular 2 : Controlling SVG Image/Icon Css Styles dynamically through user inputs/events on UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42200443/

相关文章:

javascript - jQuery - 在代码行之前查找特定元素

javascript - jQuery 切换故障排除

javascript - 如何使用 SVG 制作圆形选择框?

php - Wordpress:编辑子主题

css - 我想使用行高重叠两行文本 - 最前面的行

jquery - 如何将 jQuery 库正确添加到 Spring MVC 项目中?

javascript - 在 mousedown-mousemove 上禁用滚动(Jquery/javascript)

javascript - 我怎样才能让这个动画响应?

html - 动画在 FF 和 IE 中不工作..?

html - .table-cell 和 .table 在 IE 上显示效果不佳