изменение цвета SVG нажатием кнопки не работает для всех изображений SVG | JQuery - PullRequest
0 голосов
/ 06 ноября 2018

Мой код предназначен для изменения цвета SVG с помощью кнопки. Код работает хорошо для одного SVG, но не для всех остальных.

<text>First SVG not work</text>
<button type="button" id="Change_Blue_Circle">Change color</button>
<div id="my-div"></div>
new Vivus('my-div', {
  duration: 200,
  file: 'http://www.stirox.com/R/uploads/s.svg'
}, function() {
  alert(1);
});

$(document).on('click', '#Change_Blue_Circle', function(e) {
  e.preventDefault();

  $("#my-div svg:first path[fill='#42352c']").each(function(index) {
    $(this).css('fill', 'yellow');
  });
});

проверьте мой сайт

1 Ответ

0 голосов
/ 08 ноября 2018

Измените свой JS-код для нажатий кнопок одним из следующих:

Код JS :

function rgb2hex(rgb){
    rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
    return (rgb && rgb.length === 4) ? "#" + ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

$(document).on('click','#Change_Blue_Circle',function(e){
    e.preventDefault();
    $("#my-div svg:first path").each(function(index) {
        var fillCSSVal = '', attrFillVal = '', comparingColorValue = '#42352c';
        if( typeof $(this).css("fill") != 'undefined' ) {
            fillCSSVal = rgb2hex($(this).css("fill")).toString().toLowerCase();
        }
        if( typeof $(this).attr('fill') != 'undefined' ) {
            attrFillVal = $(this).attr('fill').toString().toLowerCase();
        }

        if( fillCSSVal == comparingColorValue || attrFillVal == comparingColorValue ) {
            $(this).css('fill', 'yellow');
        }
    });
});

$(document).on('click','#Change_Green_Circle',function(e){
    e.preventDefault();
    $("#my-div2 svg:first path").each(function(index) {
        var fillCSSVal = '', attrFillVal = '', comparingColorValue = '#9cca15';
        if( typeof $(this).css("fill") != 'undefined' ) {
            fillCSSVal = rgb2hex($(this).css("fill")).toString().toLowerCase();
        }
        if( typeof $(this).attr('fill') != 'undefined' ) {
            attrFillVal = $(this).attr('fill').toString().toLowerCase();
        }

        if( fillCSSVal == comparingColorValue || attrFillVal == comparingColorValue ) {
            $(this).css('fill', 'red');
        }
    });
});

Скрипт проверит, имеет ли SVG с элементами пути прямой атрибут как «заливка» или css со свойством «заливка» как требуемое значение цвета.

Функция rgb2hex выдаст шестнадцатеричное значение цвета из значений rgb, его ссылка взята из JS Fiddle: https://jsfiddle.net/Mottie/xcqpF/1/light/

например. rgb (255, 255, 255) будет возвращен как # fffff

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...