Как переключать разные цвета при последовательных щелчках (на объектах SVG) - PullRequest
0 голосов
/ 23 мая 2019

Я пытаюсь, чтобы все элементы в группе менялись на определенные цвета при различном количестве кликов. Один щелчок = красный, два щелчка = синий и т. Д. Необходимо переключить всех детей в группе.

JavaScript

function call1() {
    console.log('call1');
    const children = document.getElementById('btn1').children;
    $(document).ready(function(){
        $("btn1").toggle(
            function(){$("btn1").css({"fill": "red"});},
            function(){$("btn1").css({"fill": "blue"});},
            function(){$("btn1").css({"fill": "green"});
        });
    });
}

SVG файл

<g id="btn1" onclick="call1()">
    <polygon fill="#FF0013" points="366.699,131 410,56 453.301,131  "/>
    <polygon fill="#07FF00" points="323.699,656 367,581 410.301,656     "/>
    <polygon fill="#0000FF" points="409.699,656 453,581 496.301,656     "/>
    <polygon points="366.699,581 410,656 453.301,581    "/>
</g>

Я хочу, чтобы все элементы в группе SVG меняли цвета при первом щелчке на красный, во втором - на зеленый, а третий - на синий.

Ответы [ 3 ]

2 голосов
/ 23 мая 2019

Вы можете использовать модуль и оператор switch для циклического перебора каждого цвета:

var count = 0;

function call1() {
  const button = $("#btn1");
  console.log(count);
  count = count % 3 + 1;
  switch (count) {
    case 1:
      button.css("fill", "red");
      break;
    case 2:
      button.css("fill", "blue");
      break;
    case 3:
      button.css("fill", "green");
      break;
  }
}

Пример:

var count = 0;

function call1() {
  const children = $("#btn1").children();
  count = count % 3 + 1;
  switch (count) {
    case 1:
      children.css("fill", "red");
      break;
    case 2:
      children.css("fill", "blue");
      break;
    case 3:
      children.css("fill", "green");
      break;
  }
}
<svg height="1000" width="100%">
  <g id="btn1" onclick="call1()">
    <polygon fill="#FF0013" points="366.699,131 410,56 453.301,131  "/>
    <polygon fill="#07FF00" points="323.699,656 367,581 410.301,656     "/>
    <polygon fill="#0000FF" points="409.699,656 453,581 496.301,656     "/>
    <polygon points="366.699,581 410,656 453.301,581    "/>
  </g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1 голос
/ 23 мая 2019

Мне пришлось немного изменить svg, чтобы сделать эту работу, и я использовал код Кобеса в качестве отправной точки:

https://jsfiddle.net/gz9mc06r/

В svg я изменил его с помощьюсвойство 'fill' для использования 'style="fill:..."'

<svg viewBox="0 0 800 800"><g id="btn1" onclick="call1()">
    <polygon style="fill:#FF0013" points="366.699,131 410,56 453.301,131  "/>
    <polygon style="fill:#07FF00" points="323.699,656 367,581 410.301,656     "/>
    <polygon style="fill:#0000FF" points="409.699,656 453,581 496.301,656     "/>
    <polygon points="366.699,581 410,656 453.301,581    "/>
</g>

</svg>

Javascript выглядит следующим образом:

var count = 1;
window.call1 = function() {
    const button = $("#btn1 polygon");
  console.log(count);
  count = count % 3 + 1;
  switch (count) {
    case 1:
      button.css("fill", "red");
      break;
    case 2:
      button.css("fill", "blue");
      break;
    case 3:
      button.css("fill", "green");
      break;
  }
}
0 голосов
/ 23 мая 2019

Я помещаю цвета в массив.Я устанавливаю счетчик.Счетчик n ++ каждый раз при нажатии.Я устанавливаю цветовой класс для группы

n %= colors.length;
btn1.setAttribute("class", colors[n])

Пожалуйста, прочитайте комментарии в моем коде

//the array of the colors
let colors = ["tomato","gold","skyblue"];
//the attay of the polygons
let polygons = Array.from(svg.querySelectorAll("#btn1 polygon"));


let n = 0;
svg.addEventListener("click",()=>{
  //remove the fill attribute of the polygons
  polygons.forEach(p =>p.removeAttribute("fill"))
  //the color for the group fill
  n %= colors.length;
  //reset the class name for the btn1
  btn1.setAttribute("class", colors[n])
  n++
})
svg{border:1px solid;width:100px;overflow:visible}

polygon{stroke:black}


.tomato{fill:tomato}
.gold{fill:gold}
.skyblue{fill:skyblue}
<svg id="svg" viewBox="300 50 230 650" >
<g id="btn1" >
    <polygon fill="#FF0013" points="366.699,131 410,56 453.301,131"/>
    <polygon fill="#07FF00" points="323.699,656 367,581 410.301,656     "/>
    <polygon fill="#0000FF" points="409.699,656 453,581 496.301,656     "/>
    <polygon points="366.699,581 410,656 453.301,581"/>
</g>
</svg>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...