CSS Translate在mouseenter和mouseleave上闪烁

时间:2018-10-08 14:19:14

标签: javascript performance css3 css-transitions anime.js

我知道已经有很多与我有关的问题,但我只是没有设法解决。也许我的JS方法不是最好的方法,并且可能会导致闪烁,我希望获得更好的解决方案。

如果您开始随动演奏,您会很快看到它有时会闪烁。我确实设法减少了闪烁的数量,但仍然会在某些时候发生。

https://codepen.io/anon/pen/zmoeeB

HTML

<div class="container">
  <ul>
    <li class="nav-item">
      <a href="#">
        <div><span>@</span> <span>Item 1</span></div>
      </a>
    </li>
    <li class="nav-item">
      <a href="#">
        <div><span>@</span> <span>Item 2</span></div>
      </a>
    </li>
    <li class="nav-item active current">
      <a href="#">
        <div><span>@</span> <span>Item 3</span></div>
      </a>
    </li>
    <li class="nav-item">
      <a href="#">
        <div><span>@</span> <span>Item 4</span></div>
      </a>
    </li>
    <li class="nav-hover"></li>
  </ul>
</div>

CSS

.container {
  height:100%;
  width:100%;
  max-width:200px;
  position:relative;
}

ul {
  margin:0;
  padding:0;
  height:100%;
  width:100%;
}

li {
  display:block;
  width:100%;
  height:100%;
}

.nav-item a {
  height:100%;
  width:100%;
  display:block;
  text-decoration:none;
}

.nav-item a, .nav-item.active a {
  color:black;
}

.nav-item.current a{
  color:white;
}

.nav-hover {
  position:absolute;
  width:100%;
  height:28px;
  background-color:red;
  z-index:-1;
}

.nav-item a div {
  padding:5px;
}

.nav-hover {
  backface-visibility: hidden;
  transform-style: preserve-3d;
  transform: translate3d(0, 0, 0);
  transform: translateZ(0);
}

JS

$active = document.querySelector(".active");
$current = document.querySelector(".nav-hover");
$items = document.querySelectorAll(".nav-item");
$nav = document.querySelector(".container ul");

$current.style.top = $active.offsetTop+'px';

for(var i = 0; i < $items.length; i++){

  $items[i].addEventListener('mouseenter', function(){
    $active.classList.remove('current');
    this.classList.add('current');
    var navHover = anime({
      targets: $current,
      translateY: (this.offsetTop - $current.offsetTop)+'px'
    });
  });

  $items[i].addEventListener('mouseleave', function(){
    this.classList.remove('current');
    $active.classList.add('current');
  });

  $nav.addEventListener('mouseleave', function(){
    var navHover = anime({
      targets: $current,
      translateY: ($active.offsetTop - $current.offsetTop)+'px'
    });
  });

};

1 个答案:

答案 0 :(得分:0)

我能够解决问题。在运行下一个动画元素之前,先将其删除。

解决方案:

anime.remove($animatedDiv);
anime({
      targets: $div,
      translateY: 200
    });