Toggle Desaturation on image onClick in css / javascript

穿精又带淫゛_ 提交于 2020-01-03 04:19:08

问题


There is more code to each function, but these are the main lines that matter in regards to my question I believe...This is from a guys library to desaturate an image on rollover basically.

How do I change it to on click, rather than on mouseover / rollover? Here's his code...

jQuery(function($){
$cloned.closest(".DesaturateDiv").bind("mouseenter mouseleave",desevent);
}

  function desevent(event) 
  {
    if (event.type == 'mouseenter')
         $(".des.color", this).fadeOut(275);

    if (event.type == 'mouseleave')
        $(".des.color", this).fadeIn(200);
  }

I've already tried changing both if statements to a jquery toggle as well as changing the top line from .bind("mouseenter mouseleave", desevent) ... to .bind("toggle", desevent) and it still didnt work. my question is basically how to substitute mouseenter and mouseleave to onClick so the image desaturates onClick then saturates again onClick. Heres my toggle code that I put in instead of the two if's above, just incase.

$('.DesaturateDiv').toggle(function() {

$(".des.color", this).fadeOut(275);

}, function() {
$(".des.color", this).fadeIn(200);
});

Also, on a related note, could you do this with css3? here's the code to desaturate an image with css3...

 img.desaturate{
filter: grayscale(100%);
-webkit-filter: grayscale(100%); -moz-filter: grayscale(100%);
-ms-filter: grayscale(100%); -o-filter: grayscale(100%);
filter: url(desaturate.svg#greyscale);
filter: gray;
-webkit-filter: grayscale(1);
}

So my question would be how to do it oncick?

I tried img.desaturate:active{} but it didn't work?

EDIT: I tried this and think something along these lines is what I need but im sure the syntax is not correct, help??

 function desevent(event) 
  {
    i = 0;

    if( i = 0 ){
    if (event.type == 'mousedown')
         $(".des.color", this).fadeOut(275);
         i = 1;
    }

    if( i = 1 ){
    if (event.type == 'mousedown')
        $(".des.color", this).fadeIn(200);
                     i = 0;
    }
  }

回答1:


Just add a specific class to the clicked element.

.desaturate{
    transition-duration: 400ms; //and other prefixes
}
.desaturate.active{
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%); -o-filter: grayscale(100%);
    filter: url(desaturate.svg#greyscale);
    filter: gray;
    -webkit-filter: grayscale(1);
}


来源:https://stackoverflow.com/questions/12262971/toggle-desaturation-on-image-onclick-in-css-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!