如何在鼠标悬停和鼠标离开jQuery时更改切换样式

时间:2018-01-09 09:36:04

标签: jquery toggle element parent

我试过了:

$(document).ready(function(e) {
    $(body').mousemove(function (evt) {

        // i want code 1.
        $(evt.target).mouseover('background-color', 'blue');
        $(evt.target).leave('background-color', 'before color');

        // i want code 2.
        $(evt.target.parent).mouseover('background-color', 'yellow');
        $(evt.target.parent).leave('background-color', 'before color');
    }
}

我不知道这个像素化代码。 请帮帮我们!!

谢谢。

3 个答案:

答案 0 :(得分:1)

$(document).ready(function(e) {

  $('.box').on('mouseover', function() {
    $(this).css({
      'background-color': 'blue'
    });
  });

  $('.box').on('mouseout', function() {
    $(this).css({
      'background-color': 'yellow'
    });
  });
  
});
.box {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  margin: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box"></div>

答案 1 :(得分:1)

您可以改为使用hover事件:

$(".element").hover(
  function() {
    $(this).css('background-color', 'yellow'); //When mouse enter
  },
  function() {
    $(this).css('background-color', 'green'); //When mouse leave
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="element">My div</div>

答案 2 :(得分:1)

使用mouseentermouseleave添加和删除课程。

&#13;
&#13;
$('.target').mouseenter(function() {
  $(this).addClass("target1");
  $(this).parent().addClass("parent1");
}).mouseleave(function() {
  $(this).removeClass("target1");
  $(this).parent().removeClass("parent1");
});
&#13;
.target1 {
  background-color: blue
}

.parent1 {
  background-color: yellow
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
  sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt
  ut labore et dolore magnam aliquam quaerat voluptatem
  <div class="target">
    <h1>Hover me I show you a result.</h1>
  </div>
</div>
&#13;
&#13;
&#13;