繁体   English   中英

如何在SVG Circle元素中使用data- *属性

[英]How to use data-* attribute with SVG Circle element

我想在用jQuery .css()方法并通过data- *属性单击时,更新Circle元素的css属性fill (例如,从蓝色更改为红色)。

例:

的CSS

svg {
  height: 200;
  width: 200;
}
circle {
  fill: blue;
}

JAVASCRIPT

jQuery(function(){
  $(document).on("click", "[data-update]", function(){
    var circle = $(this).find("circle");
    circle.css({ fill: "red" });
  });
});

的HTML

<svg data-update>
  <circle cy="100" cx="100" r="50"></circle>
</svg>

演示的链接在这里

因此,如果我向data-update属性添加一个值(例如,绿色):

data-update="green"

那么,为了更改Circle元素的颜色,我应该在脚本中更改或添加哪些特定代码?

任何想法?

您只需要获取属性的值。 演示

jQuery(function(){
  $(document).on("click", "[data-update]", function(){
    var circle = $(this).find("circle");
    circle.css({
      fill: $(this).data('update') // <-- get value
    });
  });
});

<svg data-update="green">
  <circle cy="100" cx="100" r="50"></circle>
</svg>

如果按如下所示更改代码,则将得到结果。

jQuery(function(){
  $(document).on("click", "svg", function(){
    var circle = $(this).find("circle");
    var color = $(this).data("update");  -- Read the data-update attribute
    circle.css({ fill: color });
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM