javascript - 通过单击目标循环渐变方向

标签 javascript jquery html css

我需要通过单击目标来循环所有八个渐变方向,如下所示:

$('.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>

有什么帮助吗?

最佳答案

您可以使用background-image访问linear-gradient值。

$('.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>

关于javascript - 通过单击目标循环渐变方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60628461/

相关文章:

jquery - 如何设置时间选择器仅设置8 :30 am to 8:30 pm in bootstrap-datetimepicker. js中的时间?

jquery - Css 过渡不适用于子元素

javascript - Lodash - 使用 _.create() 的值(value)是什么

如果两个 div 具有相同的类,则 javascript 会触发

javascript - 单击时停止淡入动画并单击时停止淡出动画

jquery - 从右向左滑动div

jquery - Bootstrap 导航栏未按预期扩展(在导航栏底部)

javascript - 通过插值引用对象中的对象(Angular 2+)

javascript - 如何建立类似gmail的菜单标题

javascript - jQuery - 如何使出现/消失文本的侧边导航更流畅?