javascript javascript更改svg形状的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10090084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript to change colour of an svg shape
提问by Len
Hi is there a way of using javascript for example using buttons to change colour of an svg shape? If so could someone please guide me in the right direction thanks
嗨,有没有一种使用 javascript 的方法,例如使用按钮来更改 svg 形状的颜色?如果可以的话,请有人指导我正确的方向,谢谢
回答by Phil H
If you have a number of these shapes, then look at the d3 library, which is designed explicitly to allow you to bind data to svg attributes. A good explanation of the way it works is the Three little circlestutorial.
如果您有许多这样的形状,请查看d3 库,该库明确设计为允许您将数据绑定到 svg 属性。它的工作方式的一个很好的解释是三个小圆圈教程。
If you want to just change an attribute of an svg shape on a button click, then you need an onclick handler for the button:
如果您只想在单击按钮时更改 svg 形状的属性,那么您需要一个按钮的 onclick 处理程序:
function handleClick() {
// code to modify svg here, e.g.:
document.getElementById('svgShapeId').setAttribute('cx',150);
}
document.getElementById('buttonId').onclick = handleClick;
回答by Alexander Pavlov
回答by Phrogz
Here's an example of using JS to create animation elements to highlight colors based on mouse over/out:
http://phrogz.net/SVG/change-color-on-hover.svg
下面是使用 JS 创建动画元素以根据鼠标悬停/移出突出显示颜色的示例:http:
//phrogz.net/SVG/change-color-on-hover.svg
Here's an example of an SVG that changes lots of colors, and house some silly mouseover buttons:
http://phrogz.net/SVG/rgbhsv.svg
这是一个 SVG 的例子,它改变了很多颜色,并包含一些愚蠢的鼠标悬停按钮:http:
//phrogz.net/SVG/rgbhsv.svg
Here's an example that shows SVG in XHTML, with both native HTML widgets (an HTML5 slider) as well as draggable SVG elements (the path handles):
http://phrogz.net/SVG/area_of_path.xhtml
这是一个在 XHTML 中显示 SVG 的示例,包括原生 HTML 小部件(HTML5 滑块)以及可拖动的 SVG 元素(路径句柄):http:
//phrogz.net/SVG/area_of_path.xhtml
In general:
一般来说:
- Find elements
- Attach event handlers
- In the event handlers, adjust properties (either via setting XML attributes or via the SVG DOM)
- 查找元素
- 附加事件处理程序
- 在事件处理程序中,调整属性(通过设置 XML 属性或通过SVG DOM)