How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

妖精的绣舞 提交于 2019-11-27 04:29:27

问题


Looking to change the border color on a box..

..when the user mouses over/out..

Here's the attempted code.. Needs Work!

JQuery:

<script>
$("result").hover(
  function () {
    $(this).addClass("result_hover");
  },
  function () {
    $(this).removeClass("result_hover");
  }
);
</script>

CSS3:

<style>
  .result {
    height: 72px;
    width: 100%;
    border: 1px solid #000;
  }
  .result_hover {
    border: 1px solid #fff;
  }
</style>

HTML5:

<div class="result">
  <div class="item">
    <div id="item1">
      <i class="icon"></i>&nbsp;##
    </div>
  </div>
<div>

Thanks for looking


回答1:


You forgot the dot of class selector of result class.

Live Demo

$(".result").hover(
  function () {
    $(this).addClass("result_hover");
  },
  function () {
    $(this).removeClass("result_hover");
  }
);

You can use toggleClass on hover event

Live Demo

 $(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });



回答2:


You could just use: {in and out function callback}

$(".result").hover(function () {
    $(this).toggleClass("result_hover");
 });

For your example, better will be to use CSS pseudo class :hover: {no js/jquery needed}

.result {
    height: 72px;
    width: 100%;
    border: 1px solid #000;
  }
  .result:hover {
    background-color: #000;
  }



回答3:


Your selector is missing a . and though you say you want to change the border-color - you're adding and removing a class that sets the background-color




回答4:


You are missing the dot on the selector, and you can use toggleClass method on jquery:

$(".result").hover(
  function () {
    $(this).toggleClass("result_hover")      
  }
);


来源:https://stackoverflow.com/questions/16821564/how-to-add-remove-class-on-mouseover-mouseout-jquery-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!