js变量到css [clip-path img gallery]

问题描述 投票:2回答:1

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

由于某种原因,仅切割第一张图像。其他人保持不变。

我在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">
javascript css variables gallery clip-path
1个回答
0
投票

document.querySelector将只返回与选择器匹配的第一个元素,而是应该使用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">
© www.soinside.com 2019 - 2024. All rights reserved.