用jquery更改图像背景
我试图通过将鼠标移到另一图像上来更改我的div内部的图像。但是,当我将鼠标移过时,我无法插入第二张图像,而当我离开鼠标时,我无法将第一张图像带回。用jquery更改图像背景
HTML
<head>
<link rel="stylesheet" href="TEST.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('img').mouseenter(function(){
$(this).remove();
$(this).css("background-image", "url(http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png)");
});
$('img').mouseleave(function(){
});
});
</script>
</head>
<body>
<div>
<img src="http://www.clker.com/cliparts/3/7/d/5/1197103862376117882Gioppino_Soccer_Ball.svg.med.png"/>
</div>
</body>
$.remove
硬是将删除页面(不要删除样式)的元素。如果删除它,则可以添加背景图像。然后将其设置为空字符串以将其删除。
$(document).ready(function(){
$('img').mouseenter(function(){
$(this).css("background-image", "url(http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png)");
});
$('img').mouseleave(function(){
$(this).css("background-image", "");
});
});
有了这个:
<img class="hoverable" src="image.png"/>
你可以使用:
jQuery(function($){ // DOM Ready shorthand
var orgSrc;
$('.hoverable').hover(function(){
orgSrc = this.src;
this.src = "image2.png";
}, function(){
this.src = orgSrc;
});
});
使用data-*
属性:DEMO
$('.hoverable').hover(function(){
$(this).data('src', this.src);
this.src = "image2.png";
}, function(){
this.src = $(this).data('src');
});
使用方法前,务必在jQuery API Docs仔细一看,获得与方法和选择的名字友好。另外我建议你打印jQuery Cheat Sheet,它总是好的有一个靠近办公桌:)
$(document).ready(function(){
$(".hoverable").hover(
function() {
$(this).attr("src","http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png");
},
function() {
$(this).attr("src","http://www.clker.com/cliparts/3/7/d/5/1197103862376117882Gioppino_Soccer_Ball.svg.med.png");
}
);
});
这些谁downvoted我的回答,您可以请注明为downvotes的原因。 – Sasidharan
您还可以通过CSS只有做到这一点:
div:after{
content: url('http://www.clker.com/cliparts/3/7/d/5/1197103862376117882Gioppino_Soccer_Ball.svg.med.png');
}
div:hover:after{
content: url('http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png');
}
如果你使用精灵,它会更好。在你的例子中,需要一些时间来加载悬停的图像... – Webberig
您不能将'background'属性应用于图像本身,所以从字面上看,您的代码将无法工作(据我所知)。正如我所看到的,你是在一个div结束了你的形象,所以可能是你可以改变它是这样的:
$('div img').mouseenter(function()
{
$(this).attr('src','source_of_new_image');
}).mouseleave(function()
{
$(this).attr('src','source_of_old_image');
});
大加赞赏 –