Change the fill of all elements inside an svg using javascript

十年热恋 提交于 2019-12-08 10:46:55

问题


I would like to change the fill color of all elements inside an SVG. The elements are both type rect and polygon. I have not set a default color.

Here is a sample file:

http://www.kingoslo.com/instruments/test.svg

How can I do this most elegantly?


回答1:


If you have jQuery:

$('svg').children().css('fill', '#ffffff');

EDIT: Note that this assumes the rects and polygons are the direct children of the svg element.




回答2:


Another variant similar to the one by Robert Longson:

document.documentElement.style.fill = 'blue';

I prefer documentElement over rootElement because it's in DOM Core, and they're mostly the same.




回答3:


This worked for me while working with a complex SVG having a lot of nested elements:

$('svg').find('path, text').css('fill', '#ffffff')



来源:https://stackoverflow.com/questions/13224952/change-the-fill-of-all-elements-inside-an-svg-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!