js 变量到 css [剪辑路径图片库]

js variable to css [clip-path img gallery]

每当有人单击按钮时,我都会尝试在每个图像中创建一个随机剪辑路径。

出于某种原因,只剪切了第一张图像。其他保持不变。

我把codepen里的代码发过来剪了。

https://codepen.io/fredericopimpao/pen/ZvBOwN?editors=1111

var test = document.querySelector('.test')
window.setInterval(function(){

  var rand = Math.random()* (200 - 10) + 30;

  test.style.setProperty('--ola', rand+'%');
}, 1000);
.test{
    clip-path: polygon(var(--ola) 30%, 100% 0%, 100% 100%,0% 100%);   
}
img{width:200px;}
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

document.querySelector 将 return 只有 第一个匹配选择器的元素,相反你应该使用 document.querySelectorAll 和 运行遍历所有元素。

var test = document.querySelectorAll('.test')
window.setInterval(function() {

  var rand = Math.random() * (200 - 10) + 30;
  for (var i = 0; i < test.length; i++)
    test[i].style.setProperty('--ola', rand + '%');
}, 1000);
.test {
  clip-path: polygon(var(--ola) 30%, 100% 0%, 100% 100%, 0% 100%);
}

img {
  width: 200px;
}
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

如果你想要每个元素的不同 clip-path,只需在循环中包含随机数:

var test = document.querySelectorAll('.test')
window.setInterval(function() {

  for (var i = 0; i < test.length; i++) {
    var rand = Math.random() * (200 - 10) + 30;
    test[i].style.setProperty('--ola', rand + '%');
  }
}, 1000);
.test {
  clip-path: polygon(var(--ola) 30%, 100% 0%, 100% 100%, 0% 100%);
}

img {
  width: 200px;
}
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

另一种方法是直接更改 CSS 属性,在这种情况下,您只需要为所有元素更改一次:

var clip = document.styleSheets[0].rules[0].style;
window.setInterval(function() {

  var rand = Math.random() * (200 - 10) + 30;
  clip.setProperty('--ola', rand + '%');

}, 1000);
.test {
  clip-path: polygon(var(--ola) 30%, 100% 0%, 100% 100%, 0% 100%);
}

img {
  width: 200px;
}
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">

<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">
<img class="test" src="https://i.ytimg.com/vi/Bor5lkRyeGo/hqdefault.jpg">