仅选择当前正在用jquery悬停的元素并切换下一个元素的可见性?

时间:2019-04-09 16:48:02

标签: javascript jquery html css css3

我有一个类为.MathBox的div,下一个元素是.ypnLeftRight 每当用户将鼠标悬停在.MathBox上时,.ypnLeftRight的可见性就会切换。当只有一个.MathBox元素但有许多这样的元素时,jquery会选择类.Mathbox的所有元素,并且所有.ypnLeftRight的元素同时切换。

如何仅在当前悬停的.ypnLeftRight元素之后立即切换类为.MathBox的div?

$('.MathBox').after('<div class="ypnLeftRight"><div class="left-button">&laquo;</div><div class="right-button">&raquo;</div></div>');

$('.right-button').click(function() {
  event.preventDefault();
  $('.MathBox').animate({
    scrollLeft: "+=200px"
  }, "slow");
});

$('.left-button').click(function() {
  event.preventDefault();
  $('.MathBox').animate({
    scrollLeft: "-=200px"
  }, "slow");
});

$('.MathBox , .ypnLeftRight').hover(function() {
  $('.ypnLeftRight').show();
}, function() {
  $('.ypnLeftRight').hide();
});
/*
  $('.MathBox , .ypnLeftRight').hover(function(){
    $(this).find('.ypnLeftRight').show();
  }, function(){
    $(this).find('.ypnLeftRight').hide();
  });*/
.MathBox {
  width: 100%;
  border: dashed 1px #dddddd;
  overflow: auto;
  padding: 0 1em;
  box-sizing: border-box;
}

.ypnLeftRight {
  display: grid;
  grid-template-columns: 50% 50%;
  text-align: center;
  background: rgba(0, 0, 0, 0.5);
  height: 1.5em
}

.ypnLeftRight>div:hover {
  background: rgba(0, 0, 0, 0.8);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="postContentItem">
  1<br/>
  <div class="MathBox">
    x^2 + 3x + 30 -32x^3 +16x^4 -x^2 -55x + 60= 0<br/>text{This is the required equation obtained by solving the quadratic equation by factorization method.
  </div>
  222<br/> 222
  <br/>1<br/>
  <div class="MathBox">
    x^2 + 3x + 30 -32x^3 +16x^4 -x^2 -55x + 60= 0<br/>This is the required equation obtained by solving the quadratic equation by factorization method.
  </div>
  222<br/> 222
  <br/>
</div>

我尝试了以下方法,但似乎不起作用。

$('.MathBox , .ypnLeftRight').hover(function(){
  $(this).find('.ypnLeftRight').show();
}, function(){
  $(this).find('.ypnLeftRight').hide();
});

1 个答案:

答案 0 :(得分:1)

由于ypnLeftRight始终是隐藏的,因此不需要在其上悬停。悬停仅适用于.MathBox。其次...您需要将鼠标悬停在.MathBox的.next()上,如下所示:

$('.MathBox').hover(function(){
  $(this).next('.ypnLeftRight').show();
}, function(){
  $(this).next('.ypnLeftRight').hide();
});

OP的目的是在悬停.MathBox时使用.ypnLeftRight内部的按钮。上面的代码无法执行此操作,因为DIV不在父div中包含在一起。下面是满足OP要求的代码。

将.MathBox div括在div中

<div class="MathBoxParent">
  <div class="MathBox">
    x^2 + 3x + 30 -32x^3 +16x^4 -x^2 -55x + 60= 0<br/>text{This is the required equation obtained by solving the quadratic equation by factorization method.
  </div>
</div>

然后使用以下代码

$('.MathBoxParent').hover(function(){
  $(this).find('.ypnLeftRight').show();
}, function(){
  $(this).find('.ypnLeftRight').hide();
});