javascript循环选择特定项目

时间:2016-03-27 22:28:25

标签: javascript gsap

我试图在每个导航项目下设置正确的div来制作动画,而不是使用类" navItemUnder" - 当您将鼠标悬停在其中一个导航项上时,您可以在此代码中看到我的意思。

我想要一种方法在右侧导航项下只选择一行,同时保持我们的HTML方式。

codePen:http://codepen.io/celli/pen/bpRLRM

$(".navItem").hover(over, out);
function over(){
TweenMax.to(".navItemUnder", 1, {opacity:1.0, scaleX:1,     ease:Expo.easeOut})
}
function out(){
TweenMax.to(".navItemUnder", 1, {opacity:0.0, scaleX:.1,     ease:Expo.easeOut})
}

1 个答案:

答案 0 :(得分:1)

您可以使用 id 属性来区分元素:

http://codepen.io/anon/pen/ZWyRjg

var activeItem;

TweenMax.set(".navItemUnder", {
  opacity: 0,
  scaleX: .1,
  transformOrigin: "top left"
})

$(".navItem").hover(over, out);

function over(e) {
  activeItem = e.toElement.id;
  TweenMax.to("#" + activeItem + "_under", 1, {
    opacity: 1.0,
    scaleX: 1,
    ease: Expo.easeOut
  })
}

function out(e) {
  TweenMax.to("#" + activeItem + "_under", 1, {
    opacity: 0.0,
    scaleX: .1,
    ease: Expo.easeOut
  })
}
* {
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
}
nav {
  margin-top: 50px;
  margin-left: 50px;
}
.lines {
  float: left;
  clear: both;
  margin-left: 50px;
}
ul li {
  display: block;
  float: left;
  padding: 0 4px;
  margin: 0 4px;
  text-align: center;
}
.navItem {
  width: 46px;
  height: 26px;
  background: transparent;
  cursor: pointer;
}
.navItemUnder {
  width: 46px;
  height: 2px;
  background: green;
  padding-top: 0;
  margin-top: 0;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.18.2/TweenMax.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<nav>
  <ul>
    <li class="navItem" id="item1">Item 1</li>
    <li class="navItem" id="item2">Item 2</li>
    <li class="navItem" id="item3">Item 3</li>
    <li class="navItem" id="item4">Item 4</li>
  </ul>
</nav>

<div class="lines">
  <ul>
    <li class="navItemUnder" id="item1_under"></li>
    <li class="navItemUnder" id="item2_under"></li>
    <li class="navItemUnder" id="item3_under"></li>
    <li class="navItemUnder" id="item4_under"></li>
  </ul>
</div>