jQuery If DIV Doesn't Have Class “x”

后端 未结 7 2351
庸人自扰
庸人自扰 2020-11-27 10:54

In jQuery I need to do an if statement to see if $this doesn\'t contain the class \'.selected\'.

$(\".thumbs\").hover(function(){

$(this).stop().fadeTo(\"no         


        
7条回答
  •  感动是毒
    2020-11-27 10:58

    jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

    if (!$(this).hasClass("selected")) {
        //do stuff
    }
    

    Take a look at my example of use

    • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
    • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
    • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

    Here is the code for it

    
    
    
    
    Sandbox
    
    
    
    
    
    
    
    
    
    
    
    One div with a thumbs class
    Another one with a thumbs class

    EDIT:

    this is just a guess, but are you trying to achieve something like this?

    • Both divs start at 30% opacity
    • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
    • Clicking a div adds/removes the 'selected' class

    jQuery Code is here-

    $(function() {
    
    $('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
    $('.thumbs').hover(fadeItIn, fadeItOut);
    $('.thumbs').css('opacity', 0.3);
    
    });
    
    function fadeItIn(e) {
    if (!$(e.target).hasClass('selected')) 
     { 
        $(e.target).fadeTo('normal', 1.0); 
      } 
    }
    
    function fadeItOut(e) { 
      if (!$(e.target).hasClass('selected'))
      { 
        $(e.target).fadeTo('slow', 0.3); 
     } 
    }
    
    
    One div with a thumbs class
    Another one with a thumbs class

提交回复
热议问题