我正在尝试循环浏览一些图像并一次从中删除一个过滤器.
var h = 0; function removeGreyscale() { document.images[h].style.webkitfilter = "grayscale(0)"; document.images[h].style.filter = "grayscale(0)"; h += 1; if (h === 8) { h = 0; } } setInterval(removeGreyscale, 3000);
此代码目前无效.
看起来您需要将webkitFilter
属性中的'f'大写:
document.images[h].style.webkitFilter = "grayscale(1)"; document.images[h].style.filter = "grayscale(1)";
Chrome 仍然需要该属性的-webkit
前缀,但它应该已经在Firefox中使用了.filter
如果要循环遍历元素并从当前元素中删除过滤器并将其添加回前一个元素,则可以使用以下内容:
i % images.length
-这将让当前元素的索引,然后重置回0
当i
超过图像的数量.
(curr - 1 < 0 ? images.length : curr) - 1
- 同样,这将通过1
从当前索引或索引1
的总图像数中减去前一个元素-1
.
显然最好在这里添加/删除/切换类并避免内联样式,但是,这仍然可以用于示例目的:
var images = document.querySelectorAll('img'),
i = 0;
function removeGreyscale() {
var curr = i % images.length,
prev = (curr - 1 < 0 ? images.length : curr) - 1;
// Remove grayscale filter from the current element
images[curr].style.webkitFilter = "grayscale(0)";
images[curr].style.filter = "grayscale(0)";
// Add grayscale filter to the previous element
images[prev].style.webkitFilter = "grayscale(1)";
images[prev].style.filter = "grayscale(1)";
i++;
}
setInterval(removeGreyscale, 1000);
img {
-webkit-filter: grayscale(1);
filter: grayscale(1);
}