在JQuery CSS中使用带剪切路径的变量

时间:2018-07-25 16:16:39

标签: jquery css clip-path

如何在带有剪切路径的JQuery CSS中使用变量。我已经记录了变量的结果,它似乎与工作的CSS代码完全相同,如在img1上看到的那样。有什么想法吗?

$(document).ready(function(){

  //WORKING
  $('.img1').css({"clip-path": "polygon(30% 0%, 100% 23%, 54% 50%, 100% 100%, 70% 100%, 79% 59%, 10% 84%, 52% 49%)"});

  //NOT WORKING
  var random1 = (Math.floor(Math.random() * 100) + 1) + "%",
      random2 = Math.floor(Math.random() * 100) + 1 + "%",
      random3 = Math.floor(Math.random() * 100) + 1 + "%",
      random4 = Math.floor(Math.random() * 100) + 1 + "%",
      random5 = Math.floor(Math.random() * 100) + 1 + "%",
      random6 = Math.floor(Math.random() * 100) + 1 + "%",
      random7 = Math.floor(Math.random() * 100) + 1 + "%",
      random8 = Math.floor(Math.random() * 100) + 1 + "%",
      clippi = '"clip-path": "polygon(' +random1 + ' ' + random2 + ','+ ' ' + random3 + ' ' + random4 + ','+ ' ' + random5 + ' ' + random6 + ','+ ' ' + random7 + ' ' + random8 + ','+ ' ' + random1 + ' ' + random2 + ','+ ' ' + random3 + ' ' + random4 + ','+ ' ' + random5 + ' ' + random6  + ','+ ' ' + random7  + ' ' + random8+')"';

    console.log(clippi)
    $('.img2').css({clippi});


});
img{
  width: 40%;
}

.img1{
  border: 5px solid red;
}

.img2{
  border: 5px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img1" src="http://placekitten.com/1200/1600">
<img class="img2" src="http://placekitten.com/900/900">

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为您要向CSS函数传递字符串而不是对象。我可以通过如下更改css声明来解决您的示例:

$(document).ready(function(){

  //WORKING
  $('.img1').css({"clip-path": "polygon(30% 0%, 100% 23%, 54% 50%, 100% 100%, 70% 100%, 79% 59%, 10% 84%, 52% 49%)"});

  //NOT WORKING
  var random1 = (Math.floor(Math.random() * 100) + 1) + "%",
      random2 = Math.floor(Math.random() * 100) + 1 + "%",
      random3 = Math.floor(Math.random() * 100) + 1 + "%",
      random4 = Math.floor(Math.random() * 100) + 1 + "%",
      random5 = Math.floor(Math.random() * 100) + 1 + "%",
      random6 = Math.floor(Math.random() * 100) + 1 + "%",
      random7 = Math.floor(Math.random() * 100) + 1 + "%",
      random8 = Math.floor(Math.random() * 100) + 1 + "%",
      clippi = random1 + ' ' + random2 + ','+ ' ' + random3 + ' ' + random4 + ','+ ' ' + random5 + ' ' + random6 + ','+ ' ' + random7 + ' ' + random8 + ','+ ' ' + random1 + ' ' + random2 + ','+ ' ' + random3 + ' ' + random4 + ','+ ' ' + random5 + ' ' + random6  + ','+ ' ' + random7  + ' ' + random8;

    console.log(clippi)
    $('.img2').css({"clip-path": 'polygon('+ clippi +')'});


});
img{
  width: 40%;
}

.img1{
  border: 5px solid red;
}

.img2{
  border: 5px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img1" src="http://placekitten.com/1200/1600">
<img class="img2" src="http://placekitten.com/900/900">