首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过类使用jQuery实现悬浮div?

问如何通过类使用jQuery实现悬浮div?
EN

Stack Overflow用户
提问于 2017-02-15 13:54:26
回答 3查看 54关注 0票数 0

我有一个jQuery函数,在带有类.myshp_list_product_image的<div>的events mouseover和mouseout上,它更改了它们的src属性。

问题是,当我悬停其中一个,它也改变了其他。

我怎么才能让它只改变被盘旋的那个呢?

下面是函数的代码:

代码语言:javascript
复制
$(function() {
  $('.myshp_list_product_image').mouseover(function() {
    $('.myshp_list_product_image').each(function() {
      var $this = $(this);
      $this.attr('src', $this.attr('src').replace('1s', '2s'));
    });
  });
  $('.myshp_list_product_image').mouseout(function() {
    $('.myshp_list_product_image').each(function() {
      var $this = $(this);
      $this.attr('src', $this.attr('src').replace('2s', '1s'));
    });
  });
});
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-02-15 13:56:34

你不需要.each()在这里,把它处理掉。您只需要针对当前元素,即this。

代码语言:javascript
复制
$(function() {
    $('.myshp_list_product_image').mouseover(function() {
        var $this = $(this);
        $this.attr('src', $this.attr('src').replace('1s', '2s'));
    });
    $('.myshp_list_product_image').mouseout(function() {
        var $this = $(this);
        $this.attr('src', $this.attr('src').replace('2s', '1s'));
    });
});

我建议您使用mouseenter和mouseleave事件,用于mouseover和mouseenter之间的区别的小演示

票数 3
EN

Stack Overflow用户

发布于 2017-02-15 13:59:17

只针对当前悬停/悬停的元素,而不是对具有相同类的所有元素进行迭代。

此外,您还可以使用.hover而不是mouseover和mouseout以及.attr()的回调函数来最小化代码:

代码语言:javascript
复制
 $('.myshp_list_product_image').hover(
 function() {
    $(this).attr('src',function(i,oldattr){return oldattr.replace('1s', '2s')}); 
 }, function() {
    $(this).attr('src',function(i,oldattr){return oldattr.replace('2s', '1s')}); 
 });
票数 2
EN

Stack Overflow用户

发布于 2017-02-15 14:01:00

我将使用来自jQuery的jQuery()

代码语言:javascript
复制
$(function () {
    $('.myshp_list_product_image').hover(function () { // mouse in
        var $this = $(this);
        $this.attr('src', $this.attr('src').replace('1s', '2s'));

    }, function () { // mouse out
        var $this = $(this);
        $this.attr('src', $this.attr('src').replace('2s', '1s'));

    });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42251316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档