loop gradient directions by clicking on a target

前端 未结 3 1483
借酒劲吻你
借酒劲吻你 2021-01-29 02:11

I need to loop all of the eight gradient directions by clicking on a target, like this:

相关标签:
3条回答
  • 2021-01-29 02:28

    Instead of background, you can get the style attribute.

    $(this).attr('style')
    

    It will return "background: linear-gradient(to top,red,yellow)".

    Then you use .slice(28) to cut out "background: linear-gradient(" and .split(',')[0] to get the direction.

    let a = $(this).attr('style').slice(28).split(',')[0];
    
    0 讨论(0)
  • 2021-01-29 02:29

    You can access the linear-gradient value with 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>

    0 讨论(0)
  • 2021-01-29 02:39

    Don't over complicate it, make it simple:

    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>

    0 讨论(0)
提交回复
热议问题