在悬停显示下一个元素

时间:2018-05-21 21:51:41

标签: javascript jquery

我正在尝试显示下一个班级测试的数据。例如,当我将鼠标悬停在第二个盒子上时,它应该显示第三个等等 问题是第一个框在div内。使用next()和children(),第二个框显示第三个框但是当它悬停在第一个框时它不起作用。



$('.box').hover(
  function() {
    var element = $(this).next().children();
    text = element.attr('data');

    $(this).append('<div id="boxText">' + text + '</div>');

  },
  function() {

    $('#boxText').remove();

  }
);
&#13;
.test {
  padding: 75px;
  background: #eee;
  float: left;
  margin: 5px;
  border: solid 1px #ddd;
  cursor: pointer;
}

#boxText {
  position: absolute;
  bottom: -35px;
  left: 5px;
  width: 150px;
  text-align: center;
  background: #45719B;
  color: #FFF;
  border: solid 1px #26445F;
  font-family: Arial, Helvetica, sans-serif;
  padding: 5px 0;
}

.box {
  position: relative;
  float: left;
  margin: 0;
  padding: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div>
    <a class="box">
      <span class="test" data="first"></span>
    </a>
  </div>
</div>

<a class="box">
  <span class="test" data="second"></span>
</a>
<a class="box">
  <span class="test" data="third"></span>
</a>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

或许这样的事情?

var $boxes = $('.box');

$boxes.hover(
  function(){
    var $hoveredBox = $(this);
    //get the box at the index after our hovered index
    var $nextBox = $boxes.eq($boxes.index($hoveredBox) + 1);
    
    if ($nextBox.length) {
      $hoveredBox.append('<div id="boxText">'+ $nextBox.find('.test').attr('data') +'</div>');
    }
  },
  function(){
    $('#boxText').remove();
  }
);
.test{
    padding:75px;
    background:#eee;
    float:left;
    margin:5px;
    border:solid 1px #ddd;
    cursor:pointer;
}
#boxText{
    position:absolute;
    bottom:-35px;
    left:5px;
    width:150px;
    text-align:center;
    background:#45719B;
    color:#FFF;
    border:solid 1px #26445F;
    font-family:Arial, Helvetica, sans-serif;
    padding:5px 0;
}

.box{
    position:relative;
    float:left;
    margin:0;
    padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<a class="box">
    <span class="test" data="first"></span>
</a>
</div>
</div>

<a class="box">
    <span class="test" data="second"></span>
</a>
<a class="box">
    <span class="test" data="third"></span>
</a>