首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在父级悬停时更改img src

在父级悬停时更改img src
EN

Stack Overflow用户
提问于 2015-08-07 14:38:52
回答 5查看 1.2K关注 0票数 0

我有以下html

代码语言:javascript
复制
<div class="custom text-center threeBox ofsted">
  <a class="ofsted" title="ofsted report" href="http://reports.ofsted.gov.uk/">
    <img class="text-center ofstedLogo" src="images/ofsted_good_transparent.png" alt="ofsted good rating">
    <h3>Ofsted</h3>
    </a>
</div>

我编写了以下jquery,它在悬停时交换背景颜色:

代码语言:javascript
复制
    $(".threeBox a").hover(
        function(){ // Mouse Over
            $(this).parent().addClass("swapBg");
        },
        function(){ // Mouse Out
            $(this).parent().removeClass("swapBg");
        }
    );

这很好,但我需要将悬停时的img.ofstedLogo src交换为“OFSTED_img.ofstedLogo_logo.jpg”。我尝试了几次对jQuery代码的更改,但都无法让它正常工作。有什么想法吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-08-07 14:42:22

您可以使用find()获取用于更改图像源的imgattr()

代码语言:javascript
复制
$(".threeBox a").hover(
        function(){ // Mouse Over
            $(this).parent().addClass("swapBg").find('img').attr('src','OFSTED_good_logo.jpg');
        },
        function(){ // Mouse Out
            $(this).parent().removeClass("swapBg").find('img').attr('src','images/ofsted_good_transparent.png');
        }
    );
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="custom text-center threeBox ofsted">
  <a class="ofsted" title="ofsted report" href="http://reports.ofsted.gov.uk/">
    <img class="text-center ofstedLogo" src="images/ofsted_good_transparent.png" alt="ofsted good rating">
    <h3>Ofsted</h3>
    </a>
</div>

票数 4
EN

Stack Overflow用户

发布于 2015-08-07 14:41:06

使用attr()

代码语言:javascript
复制
$(".threeBox a").hover(
        function(){ // Mouse Over
            $(this).parent().addClass("swapBg");
            $(this).find('img').attr('src', 'images/OFSTED_good_logo.jpg');
        },
        function(){ // Mouse Out
            $(this).parent().removeClass("swapBg");
            $(this).find('img').attr('src', 'images/ofsted_good_transparent.png');
        }
    );
票数 2
EN

Stack Overflow用户

发布于 2015-08-07 14:41:19

这将完成以下工作:

代码语言:javascript
复制
$(this).children('.ofstedLogo').attr('src', 'yourimagehere.png');

请参阅attr

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

https://stackoverflow.com/questions/31880425

复制
相关文章

相似问题

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