一旦使用jQuery悬停指定的元素,将图像变为黑白并恢复正常

时间:2012-10-26 23:13:10

标签: jquery css image

标题几乎说明了一切。 我经历了一些jQuery插件,以便将图像变成黑白图像。 但它们都没有提供我想到的功能。当指定的元素悬停时,我希望图像变回彩色图像。

这是我目前使用的插件:

(function ($) {
$.fn.extend({
    BlackAndWhite: function (options) {
        'use strict';
        var container = this,
            self = this,
            defaults = {
                hoverEffect: true,
                webworkerPath: false,
                responsive: true,
                invertHoverEffect: false,
                speed: 500
            };
            options = $.extend(defaults, options);
        //@public vars
        var hoverEffect = options.hoverEffect,
            webworkerPath = options.webworkerPath,
            invertHoverEffect = options.invertHoverEffect,
            responsive = options.responsive,
            fadeSpeedIn = $.isPlainObject(options.speed) ? options.speed.fadeIn : options.speed,
            fadeSpeedOut = $.isPlainObject(options.speed) ? options.speed.fadeOut : options.speed;
        //@private var
        var supportsCanvas = !!document.createElement('canvas').getContext,
            $window = $(window);
        /* Check if Web Workers are supported */
        var supportWebworker = (function () {
                return (typeof (Worker) !== "undefined") ? true : false;
            }());

        var isIE7 = $.browser.msie && +$.browser.version === 7;
        //@private methods
        //convert any image into B&W using HTML5 canvas
        var greyImages = function (img, canvas, width, height) {
            var ctx = canvas.getContext('2d'),
                currImg = img,
                i = 0,
                grey;

            ctx.drawImage(img, 0, 0, width, height);

            var imageData = ctx.getImageData(0, 0, width, height),
                px = imageData.data,
                length = px.length;

            // web worker superfast implementation
            if (supportWebworker && webworkerPath) {

                var BnWWorker = new Worker(webworkerPath + "BnWWorker.js");

                BnWWorker.postMessage(imageData);

                BnWWorker.onmessage = function (event) {
                    ctx.putImageData(event.data, 0, 0);
                };
            } else {

                // no webworker slow implementation
                for (; i < length; i += 4) {
                    grey = px[i] * 0.3 + px[i + 1] * 0.59 + px[i + 2] * 0.11;
                    px[i] = px[i + 1] = px[i + 2] = grey;
                }

                ctx.putImageData(imageData, 0, 0);
            }
        };

        var injectTags = function (pic, currImageWrapper) {

            var src = pic.src;

            if (supportsCanvas && (!($.browser.msie && $.browser.version == '9.0'))) {

                var currWidth = $(currImageWrapper).find('img').width(),
                    currHeight = $(currImageWrapper).find('img').height(),
                    realWidth = pic.width,
                    realHeight = pic.height;

                //adding the canvas
                $('<canvas width="' + realWidth + '" height="' + realHeight + '"></canvas>').prependTo(currImageWrapper);
                //getting the canvas
                var currCanvas = $(currImageWrapper).find('canvas');
                //setting the canvas position on the Pics
                $(currCanvas).css({
                    'position': 'absolute',
                    top: 0,
                    left: 0,
                    width: currWidth,
                    height: currHeight,
                    display: invertHoverEffect ? 'none' : 'block'
                });

                greyImages(pic, currCanvas[0], realWidth, realHeight);

                if (hoverEffect) {
                    $(currImageWrapper).mouseenter(function () {
                        if(!invertHoverEffect) {
                            $(this).find('canvas').stop(true, true).fadeOut(fadeSpeedOut);
                        } else {
                            $(this).find('canvas').stop(true, true).fadeIn(fadeSpeedIn);
                        }
                    });
                    $(currImageWrapper).mouseleave(function () {
                        if(!invertHoverEffect) {
                            $(this).find('canvas').stop(true, true).fadeIn(fadeSpeedIn);
                        } else {
                            $(this).find('canvas').stop(true, true).fadeOut(fadeSpeedOut);
                        }
                    });
                }
            } else {

                var ieWidth = $(currImageWrapper).find('img').prop('width');
                var ieHeight = $(currImageWrapper).find('img').prop('height');

                //adding the canvas
                $('<img src=' + src + ' width="' + ieWidth + '" height="' + ieHeight + '" class="ieFix" /> ').prependTo(currImageWrapper);
                $('.ieFix').css({
                    'position': 'absolute',
                    top: 0,
                    left: 0,
                    'filter': 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)',
                    display: invertHoverEffect ? 'none' : 'block'
                });

                if (hoverEffect) {
                    $(currImageWrapper).mouseenter(function () {
                        if(!invertHoverEffect) {
                            $(this).children('.ieFix').stop(true, true).fadeOut(fadeSpeedOut);
                        } else {
                            $(this).children('.ieFix').stop(true, true).fadeIn(fadeSpeedIn);
                        }
                    });
                    $(currImageWrapper).mouseleave(function () {
                        if(!invertHoverEffect) {
                            $(this).children('.ieFix').stop(true, true).fadeIn(fadeSpeedIn);
                        } else {
                            $(this).children('.ieFix').stop(true, true).fadeOut(fadeSpeedOut);
                        }
                    });
                }
            }
        };
        this.init = function (options) {

            $(container).each(function (index, currImageWrapper) {
                var pic = new Image();
                pic.src = $(currImageWrapper).find('img').prop("src");

                if (!pic.width) {
                    $(pic).on("load", function() {injectTags( pic, currImageWrapper);});
                } else {
                    injectTags( pic, currImageWrapper );
                }
            });


            if (responsive) {
                $window.on('resize orientationchange', container.resizeImages);
            }
        };

        this.resizeImages = function () {

            $(container).each(function (index, currImageWrapper) {
                var pic = $(currImageWrapper).find('img:not(.ieFix)');
                var currWidth,currHeight;
                if (isIE7) {
                    currWidth = $(pic).prop('width');
                    currHeight = $(pic).prop('height');
                } else {
                    currWidth = $(pic).width();
                    currHeight = $(pic).height();
                }

                $(this).find('.ieFix, canvas').css({
                    width: currWidth,
                    height: currHeight
                });

            });
        };

        return self.init(options);

    }

});
}(jQuery));

3 个答案:

答案 0 :(得分:2)

我认为你也可以通过使用CSS3来做到这一点。为了制作任何图像(假设它有类&#34;图像&#34;)为黑色和白色,您可以使用: -

img.Image{
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
filter: grayscale(100%);
}

并且在悬停时将其变回彩色的,你可以这样做: -

img.Image:hover{
-webkit-filter: grayscale(0%);
-moz-filter: grayscale(0%);
filter: grayscale(0%);
}

答案 1 :(得分:1)

通过Jquery,可以通过以下方式实现同​​样的目标: -

要使图像变为黑白,请执行以下操作: -

如果你想在文件准备就绪,那么

$('document').ready(function(){
 $("img.Image").css({'-webkit-filter':'grayscale(100%)','-moz- filter':'grayscale(100%)','filter': 'grayscale(100%)'});    
});

那么你需要我认为是这样的: -

$("img.Image").on('hover',function(){
$(this).css({'-webkit-filter':'grayscale(0%)','-moz-filter':'grayscale(0%)','filter':'grayscale(0%)'});
},function(){
$(this).css({'-webkit-filter':'grayscale(100%)','-moz-filter':'grayscale(100%)','filter': 'grayscale(100%)'});
}
);

答案 2 :(得分:0)

Convert an image to grayscale in HTML/CSS建议通过平均红色,绿色和蓝色组件来对Firefox中的图像进行灰度化。然而,这不会导致具有相同亮度的图像。使用去饱和过滤器可以获得更好的结果:

<svg xmlns="http://www.w3.org/2000/svg">
  <filter id="gray">
    <feColorMatrix type="saturate" values="0"/>
  </filter>
</svg>

在CSS中使用filter: url(grayscale.svg#grayscale);。 (如果您的文档非常简单,那么您实际上可以将HTML,CSS和SVG放在同一文档中。)