问题描述
我有以下HTML
<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,它在a悬停时交换背景颜色:
$(".threeBox a").hover(
function(){ // Mouse Over
$(this).parent().addClass("swapBg");
},
function(){ // Mouse Out
$(this).parent().removeClass("swapBg");
}
);
效果很好,但我需要将鼠标悬停时将img.ofstedLogo src交换为'OFSTED_good_logo.jpg'。 我已经尝试过对jQuery代码进行一些更改,但无法使其正常工作。 有什么想法吗?
1楼
您可以使用获取img
和来更改图像源
$(".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'); } );
<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>
2楼
使用
$(".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');
}
);
3楼
这将完成工作:
$(this).children('.ofstedLogo').attr('src', 'yourimagehere.png');
见
4楼
使用选择图像,然后使用更改src属性:
$(".threeBox a").hover(
function(){ // Mouse Over
$(this).parent().addClass("swapBg");
$(this).find('img.ofstedLogo').attr("src", "images/OFSTED_good_logo.jpg");
},
function(){ // Mouse Out
$(this).parent().removeClass("swapBg");
$(this).find('img.ofstedLogo').attr("src","images/ofsted_good_transparent.png");
}
);
5楼
有几种方法可以通过图形来实现此效果。在此处查看jsfiddle示例:
jQuery直接图像替换
$(".twoBox > a").hover(
function(){ // Mouse Over
$(this).find('img:first').attr("src", 'http://blog.modernica.net/wp-content/uploads/2011/12/2-300x300.png');
},
function(){ // Mouse Out
$(this).find('img:first').attr("src", 'http://www.adamcentric.com/wp-content/uploads/2014/09/1-300x300.png');
}
);
或jQuery CSS类交换
.ofstedLogo2 {
height: 300px;
width:300px;
background-image:url(http://www.adamcentric.com/wp-content/uploads/2014/09/1-300x300.png);
}
.ofstedLogo3 {
height: 300px;
width:300px;
background-image:url(http://blog.modernica.net/wp-content/uploads/2011/12/2-300x300.png);
}
$(".threeBox > a").hover(
function(){ // Mouse Over
$(this).find('div:first').toggleClass("ofstedLogo2");
$(this).find('div:first').toggleClass("ofstedLogo3");
},
function(){ // Mouse Out
$(this).find('div:first').toggleClass("ofstedLogo2");
$(this).find('div:first').toggleClass("ofstedLogo3");
}
);
一种是使用实际的IMG src替换,另一种是使用css背景图像方法。