简体   繁体   中英

jQuery adding a class - all methods I've tried remove the class on click

I'm working with a 3D rotating button in which each face has a different phrase, but both are links to the same URL. I initially was rotating the cube button with a plain old css :hover, but I noticed that when you click the button it resets. It should only rotate back to its starting position if your mouse is no longer on the button.

I have created a pen that uses all of my markup and styling, and I've tried four methods of adding a class called 'flip' to style on hover, but each of these four methods have the same effect as the plain old css :hover method, they reset on a mouse click. I've commented #2, 3, and 4 out in the pen just because they are all yielding the same result, and the first is just a simple 'toggleClass' method. Here's the four JS snippets and a link to the pen.

// #1 Story Button Toggle Class On Hover To Rotate - Resets on Click
    $('.story-button').hover(function () {
      $(this).toggleClass('flip');
      return false;
  });

// #2 Story Button Add/Remove Class On Hover To Rotate - Resets on Click
$('.story-button').hover(
  function () {
    $(this).addClass('flip');
  },
  function () {
    $(this).removeClass('flip');
  }
);

// #3 Story Button Add/Remove Class on 'mouseover To Rotate - F's Up the markup/styles on mouseover
$('.story-button').mouseover(function(){
    $(this).removeClass().addClass('flip');
    }).mouseout(function(){
    $(this).removeClass().addClass('flip');       
});

// #4 Story Button Add/Remove Class on 'mouseenter' and 'mouseleave' To Rotate - Still Rotates back on click
 $('.story-button')
    .mouseenter(function() {   
        $(this).addClass('flip');
    })
    .mouseleave(function() {
        $(this).removeClass('flip');
 });

And the link to the pen: http://codepen.io/andandandandrew/pen/OPXOxP?editors=011

Thanks in advance for the help/advice!

PS, If anyone has any idea why this would work on codepen but not on my local mamp server (building a wordpress site, using codekit with no JSHint errors when compiled/minified) that would be super.

The problem is that the hover event is on the element that is being transformed if you add a div around the button and listen for the hover on the div then you shouldn't have a problem.

HTML:

<div class="btnContainter">
   <button class="story-button">
      <a class="front" href="javascript:(void)">FRONT</a>
      <a class="back" href="javascript:(void)">BACK</a>
   </button>
</div>

CSS:

.btnContainter {
   display: block;
   width: 15em;
   height: 3em;
   margin: 0 auto;
}

jQuery:

$('.btnContainter').hover(function () {
    $(this).children('.story-button').toggleClass('flip');
    return false;
);

codePen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM