提问者:小点点

仅更改当前元素的类(jQuery+this)


我需要改变类在悬停只为当前元素,可能与'this'。 这里是工作代码,但是它更改了所有元素的类。

https://codepen.io/kylokean/pen/xwxewjl

<a href="#" class="change_img_wrap">
      <img src="https://cdn.iconscout.com/icon/free/png-256/google-keep-2-569459.png" class="img-regular">
        <img src="https://img.icons8.com/material/4ac144/256/user-male.png" class="img-hover">
</a>

<a href="#" class="change_img_wrap">
  <img src="https://cdn.iconscout.com/icon/free/png-256/google-keep-2-569459.png" class="img-regular">
    <img src="https://img.icons8.com/material/4ac144/256/user-male.png" class="img-hover">
</a>

<style>

.img-hover {
  display: none !important;
} 

.hideme {
  display: none !important;
}

.showme {
  display: block !important;
}

.change_img_wrap {
  display: inline-block;
} 

</style>

<script>

        jQuery(".change_img_wrap").hover(function() {
            jQuery(".img-regular").toggleClass("hideme");
        jQuery(".img-hover").toggleClass("showme");

        });

</script>

共2个答案

匿名用户

jQuery(".change_img_wrap").hover(function() {
  $(this).find(".img-regular").toggleClass("hideme");
  $(this).find(".img-hover").toggleClass("showme");
});

匿名用户

你试过使用on事件而不是悬停吗?例如:

jQuery(".change_img_wrap").on("mouseover", function() {
    jQuery(".img-regular").toggleClass("hideme");
    jQuery(".img-hover").toggleClass("showme");
 });