使用javascript从图像中删除灰度css过滤器

removing greyscale css filter from images with javascript

本文关键字:灰度 css 过滤器 删除 javascript 图像 使用      更新时间:2023-09-26

我正在尝试循环浏览一些图像,并一次从中删除一个过滤器。

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仍然需要filter属性的-webkit前缀,但它应该已经在Firefox中工作了。


如果你想在元素上循环,从当前元素中删除过滤器,并将其添加回上一个元素,那么你可以使用以下方法:

  • i % images.length-这将获得当前元素的索引,然后在i超过图像数时重置回0

  • (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);
}
<img src="//placehold.it/200/f00" />
<img src="//placehold.it/200/0f0" />
<img src="//placehold.it/200/00f" />

CSS专用解决方案:http://jsfiddle.net/t2zaf1fk/2/

HTML:

<img src="//placehold.it/200/f00" />
<img src="//placehold.it/200/0f0" />
<img src="//placehold.it/200/00f" />

CSS:

img {
    -webkit-animation: fade 3s linear 0 infinite;
    -webkit-filter: grayscale(1);        
}
img:nth-child(1) {
    -webkit-animation-delay:1s;
}
img:nth-child(2) {
    -webkit-animation-delay:2s
}
@-webkit-keyframes fade {
    0% {
        -webkit-filter: grayscale(1);    
    }
    65% {
        -webkit-filter: grayscale(1);    
    }
    66% {
        -webkit-filter: none;    
    }
    100% {
        -webkit-filter: none;    
    }
}