每当有人单击按钮时,我都会尝试在每个图像中创建一个随机剪辑路径。
出于某种原因,只有第一张图片被剪切了。其他保持不变。
我在 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
将返回仅匹配选择器的第一个元素,相反,您应该使用 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">
关于javascript - js 变量到 css [剪辑路径图片库],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47955598/