SVG linearGradient DOM仅适用于Chrome

我正在尝试使用jquery更改svg linearGradient的颜色,但我的代码仅适用于Chrome。

任何人都可以帮助我在这里跨浏览器吗?

$(document).ready(function() { $(".input-holder:first .form-control").focusout(function(e) { var colorValue = $(this).val(); var s = "#" + colorValue; var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/; var matches = patt.exec(s); var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")"; $(this).next(".color-rgba").html(rgb); var getColor = $("lineargradient#grad1 stop:first").css('stop-color'); //alert(getColor); $("lineargradient#grad1 stop:first").css('stopColor',rgb); }); $(".input-holder:eq(1) .form-control").focusout(function(e) { var colorValue = $(this).val(); var s = "#" + colorValue; var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/; var matches = patt.exec(s); var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")"; $(this).next(".color-rgba").html(rgb); $("lineargradient#grad1 stop:eq(1)").css('stopColor',rgb); //$("lineargradient#grad1 stop:eq(1)").css('-moz-stop-color',rgb); }); }); 
  
Sorry, your browser does not support inline SVG.

SVG区分大小写,因此它的线性渐变而不是线性渐变。 换句话说,你应该需要这个:

 $("linearGradient#grad1 stop:eq(1)").css('stopColor',rgb); 

不幸的是,这不适用于Chrome,因为Chrome错误地要求元素名称小写。

Chrome的常用解决方法是为所有linearGradientElements提供一个linearGradient类,然后按类而不是按元素名称进行选择。 在你的情况下,因为你给了渐变一个id,你可以使用它。

 $(document).ready(function() { $(".input-holder:first .form-control").focusout(function(e) { var colorValue = $(this).val(); var s = "#" + colorValue; var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/; var matches = patt.exec(s); var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")"; $(this).next(".color-rgba").html(rgb); var getColor = $("#grad1 stop:first").css('stop-color'); //alert(getColor); $("#grad1 stop:first").css('stopColor',rgb); }); $(".input-holder:eq(1) .form-control").focusout(function(e) { var colorValue = $(this).val(); var s = "#" + colorValue; var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/; var matches = patt.exec(s); var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")"; $(this).next(".color-rgba").html(rgb); $("#grad1 stop:eq(1)").css('stopColor',rgb); //$("#grad1 stop:eq(1)").css('-moz-stop-color',rgb); }); }); 
  
Sorry, your browser does not support inline SVG.