首页 > 解决方案 > How can I trigger each link in a list of hyperlinks to animate on click (tap on touchscreens)

问题描述

I have a list of links to which I don't want to apply any animation on hover but do want to apply an "outro" animation on click. I've got the animation to do what I want it to do, but clicking on any link moves the entire list as a unit, which, of course, is not the point of a list of links. I'm sure this requires a simple jquery tweak, but I can barely read jquery, much less write it. If someone can tell me why this is going wrong (and how to fix it), I would be grateful. Here're the deets:

<div class="content-wrapper">
   <div class="stage">
   <ul class="all-links">
     <li class='each-link'><a class="thankyou" href="https://google.com" target="_blank" rel="noopener">Google</a></li>
     <li class="each-link"><a class="thankyou" href="https://wikipedia.org" target="_blank" rel="noopener">Wikipedia</a></li>
     <li class="each-link">
       <a class="thankyou" href="https://goodreads.com" target="_blank" rel="noopener">Goodreads</a></li>
   </ul>
 </div>
</div>
*, *:before, *:after {
  margin: 0;
  padding: 0;
}

.content-wrapper {
  position: relative;
  width: 100%;
  height: 100vh;
  background: #c4a278;
}

.stage {
  position: absolute;
  top: 30px;
  left: 5%; 
  width: 500px;
  height: auto;
  overflow: hidden;
}


ul.all-links {
  list-style: none;
  width: 100%;
  overflowX:hidden;
}

.each-link {
   position: relative;
  top: 0;
  left: 0;
  display: block;
}

a.thankyou {
 color: #762500;
  white-space: nowrap;
  font-family: 'raleway', sans-serif;
    text-align: left;
  font-size: .9em;
  line-height: 1.4em;
  z-index: 2;
  text-decoration: none;
}

.road-runner {
    animation: beep-beep 2.51s ease-in forwards;
}

@keyframes beep-beep {
   0% {
  left: 0%
  }
  
  4% {
    transform: translateY(-1vh);
  }
  
  8% {
    transform: translateY(0);
  }
  
  12% {
    transform: translateY(-1vh);
  }
  
  16% {
    transform: translateY(0);
    left: 0%;
  }
  
  21% {
   transform: skewX(0deg); 
  }
  
  25% {
    transform: skewX(-40deg);
  }
  
  100% {
   left: 100%;
    transform: skewX(-40deg);
  }
}

$(document).ready(function(){
        $("a").click(function(){
            $(".each-link").addClass("road-runner");
        });


        $('.each-link').on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
             $(this).removeClass("road-runner");
        });
    });

标签: javascripthtmljquerycss

解决方案


This selects all links on your entire webpage. Probably not what you want.

$("a")

Fix:

// Select every anchor with a parent that has the "each-link" class.
$(".each-link a").click(function() {
  // Add class to the the parent of the currently clicked link with "each-link" class.
  $(this).closest(".each-link").addClass("road-runner");
});

推荐阅读