L oop градиент направления, нажав на цель - PullRequest
0 голосов
/ 11 марта 2020

Мне нужно l oop по всем направлениям градиента восемь , нажав на цель, например:

$('.targ').on('click', function() {
  let a = $(this).css('background').split(',')[0];
  console.log(a); // I need `to top` here
  if (a == 'to top') {
    a = 'to top right'
  } else if (a == 'to top right') {
    a = 'to right'
  } else if (a == 'to right') {
    a = 'to right bottom'
  }
  // and so on
  $(this).css('background', 'linear-gradient' + new_value);
});
.targ {
  width: 54px;
  height: 54px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='targ' style='background: linear-gradient(to top,red,yellow)'></div>

Любая помощь?

Ответы [ 3 ]

1 голос
/ 11 марта 2020

Вы можете получить доступ к значению linear-gradient с помощью background-image.

$('.targ').on('click', function() {
  let direction = $(this).css('background-image').split(',')[0].slice(16);
  const gradientColors = $(this).css('background-image').split(',').slice(1);

  if (direction == 'to top') {
    direction = 'to top right'
  } else if (direction == 'to top right') {
    direction = 'to right'
  } else if (direction == 'to right') {
    direction = 'to right bottom'
  }

  $(this).css('background', 'linear-gradient(' + direction + ',' + gradientColors.join(','));
});
.targ {
  width: 54px;
  height: 54px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='targ' style='background: linear-gradient(to right,red,yellow)'></div>
1 голос
/ 11 марта 2020

Вместо фона вы можете получить атрибут стиля.

$(this).attr('style')

Он вернет "background: linear-gradient(to top,red,yellow)".

Затем вы используете .slice(28), чтобы вырезать "background: linear-gradient(" и .split(',')[0], чтобы получить направление.

let a = $(this).attr('style').slice(28).split(',')[0];
0 голосов
/ 11 марта 2020

Не усложняйте, сделайте это просто:

var c=0;

document.querySelector('.targ').addEventListener('click',function(e) {
  e.target.style.setProperty('--d',(c+=90)+"deg");
})
.targ {
  width: 54px;
  height: 54px;
  cursor: pointer;
  background: linear-gradient(var(--d,0deg),red,yellow)
}
<div class='targ' style=''></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...