(我知道这是一篇旧帖子,但为了记录……)
如果您想立即从彩色切换到灰度,请查看this thread。如果要逐渐切换它们,请使用 jquery 和 canvas。
这是一个基于HTML5 Grayscale Image Hover 站点的示例代码,因为他们的版本只支持
元素,我做了这个代码来使用'background' css 规则:
HTML:
<div class="gray"></div>
CSS:
div.gray {
width: 300px;
height: 00px;
opacity: 0;
background-image: url(images/yourimage.jpg);
}
JS:
jQuery(function() {
$ = jQuery;
// On window load. This waits until images have loaded which is essential
$(window).load(function(){
// Fade in images so there isn't a color "pop" document load and then on window load
$("div.gray").animate({opacity:1},500);
// clone colored image, convert it to grayscale and place the cloned one on top
$('div.gray').each(function(){
var div = $(this);
var bg = div.css('background-image');
bg = /^url\((['"]?)(.*)\1\)$/.exec(bg);
bg = bg ? bg[2] : "";
if(bg) {
var el = $("<div></div>");
div.append(el);
el.addClass('color').css({
"position":"absolute",
"z-index":"100",
"opacity":"0",
"background-image":"url('"+bg+"')"
});
div.css('background-image',"url('"+grayscale(bg)+"')");
}
});
// Fade image
$('div.gray').mouseover(function(){
var div = $(this);
div.find('div.color').css({
"width":div.width(),
"height":div.height(),
"top":div.position().top,
"left":div.position().left,
}).stop().animate({opacity:1}, 1000);
})
$('div.color').mouseout(function(){
$(this).stop().animate({opacity:0}, 1000);
});
});
// Grayscale w canvas method
function grayscale(src){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0);
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
});
“url(...)”解析器是从this thread 获得的。它不处理任何类型的值,但适用于简单路径。您可以修改正则表达式。如果您需要更多。
可以在 JSBin 中查看示例代码:http://jsbin.com/qusotake/1/edit?html,css,js
但是由于域限制(带有图像),它不起作用。请下载代码和图片并在您的本地网络服务器中执行。