La solution choisie convient si vous voulez que jQuery traite tous les éléments svg de votre DOM et si votre DOM est de taille raisonnable. Mais si votre DOM est grand et que vous décidez de charger des parties de votre DOM dynamiquement, cela n'a vraiment aucun sens de devoir rescanner le DOM entier juste pour mettre à jour les éléments svg. Utilisez plutôt un plugin jQuery pour effectuer cette opération :
/**
* A jQuery plugin that loads an svg file and replaces the jQuery object with its contents.
*
* The path to the svg file is specified in the src attribute (which normally does not exist for an svg element).
*
* The width, height and class attributes in the loaded svg will be replaced by those that exist in the jQuery object's
* underlying html. Note: All other attributes in the original element are lost including the style attribute. Place
* any styles in a style class instead.
*/
(function ($) {
$.fn.svgLoader = function () {
var src = $(this).attr("src");
var width = this.attr("width");
var height = this.attr("height");
var cls = this.attr("class");
var ctx = $(this);
// Get the svg file and replace the <svg> element.
$.ajax({
url: src,
cache: false
}).done(function (html) {
let svg = $(html);
svg.attr("width", width);
svg.attr("height", height);
svg.attr("class", cls);
var newHtml = $('<a></a>').append(svg.clone()).html();
ctx.replaceWith(newHtml);
});
return this;
};
}(jQuery));
Dans votre html, spécifiez un élément svg comme suit :
<svg src="images/someSvgFile.svg" height="45" width="45" class="mySVGClass"/>
Et appliquer le plugin :
$(".mySVGClass").svgLoader();
2 votes
Malheureusement, la balise img ne fonctionne pas avec les fichiers svg dans IE, il faut donc en tenir compte. IE reconnaît les balises embed. Quoi qu'il en soit, bon travail !
3 votes
Pour les svg, vous devez utiliser la propriété css "fill". Pour les images, il est approprié d'utiliser "filter". En fait, "Filter" fonctionne pour les deux, mais il est inutile de faire tout ce travail pour un graphique vectoriel.