使用Jquery进行翻转时更改DIV背景 [英] Change DIV Background on rollover with Jquery
问题描述
我对JQuery还是很陌生,但是已经很喜欢它了.
I am very new to JQuery but already like it a lot.
当用户将鼠标悬停时,我正在尝试更改div的背景.但是我无法更新bg.到目前为止,这就是我所拥有的:
I am trying to change a background of a div when the user rollsovers it. But I can not get the bg to update. So far this is what I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#fish{background-image:url(images/fish_off.jpg);width:459px;height:474px;}
</style>
<script type="text/javascript" src="javascript/jquery.js"></script>
<script type="text/javascript">
$('#fish').hover(
function(){$('#fish').css({background: "url(images/fish_on.jpg)"})},
function(){$('#fish').css({background: "url(images/fish_off.jpg)"})}
);
</script>
</head>
<body>
<div id="fish"></div>
</body>
</html>
这是我的测试页,根据下面的信息,我仍然遇到问题:
Here is my test page and based off the info below I am still having issues:
推荐答案
使用.mouseenter(),或者如果您希望在mouseout上应用一个类,也请使用.hover() http://api.jquery.com/mouseenter/ http://api.jquery.com/hover/
use .mouseenter() or if you want to apply a class on mouseout as well use .hover() http://api.jquery.com/mouseenter/ http://api.jquery.com/hover/
$("div").hover(
function () {
$(this).css("background", "#ddd");
},
function () {
$(this).css("background", "#ccc");
}
);
如果您只想要滚动,也可以完全通过CSS进行操作
you can also do this purely through css if you just want a rollver
#fish { background: #fff;
#fish:hover { background: #ccc; }
查看有关使用悬停的工作小提琴 http://jsfiddle.net/faLdY/
check out this working fiddle on using hover http://jsfiddle.net/faLdY/
通过jquery应用背景图片略有不同 查看这个类似的问题 使用jQuery切换DIV背景图像
Applying background images via jquery is slightly different checkout this similar question Switching a DIV background image with jQuery
请注意,您在示例页面中应用CSS的方式是错误的.
note the way the css is applied in your example page you are doing it incorrectly.
更改
$('#fish').hover(
function(){$('#fish').css({background: "url(images/fish_on.jpg)"})},
function(){$('#fish').css({background: "url(images/fish_off.jpg)"})}
);
对此
$('#fish').hover(
function(){$('#fish').css("background-image", "url(images/fish_on.jpg)")},
function(){$('#fish').css("background-image", "url(images/fish_off.jpg)")}
);
这是一个正在工作的小提琴,正好按照您的要求进行 http://jsfiddle.net/C7KxR/
Here is a working fiddle doing exactly what you asked http://jsfiddle.net/C7KxR/
这直接链接到您的图片,顺便说一句.我希望那没事.
this is linked directly to your images, btw. I hope thats alright.
这篇关于使用Jquery进行翻转时更改DIV背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!