【问题标题】:Change CSS3 Background image on <p> hover在 <p> 悬停时更改 CSS3 背景图像
【发布时间】:2011-08-11 19:27:42
【问题描述】:
当我将鼠标悬停在某个段落上时,我正在尝试更改背景图像(我使用 CSS3“背景”和“背景大小”设置)。
我试过了:
在 jQuery 中
$(function () {
$('#web').hover(function () {
$(this).css('background', '#000 url(space-image.png) center center fixed no-repeat');
})
});
在 Javascript 中
onMouseOver="document.getElementByName("body").style.backgroundColor = 'red';
以及其他没有运气的人。
【问题讨论】:
标签:
javascript
jquery
css
【解决方案1】:
首先,
$(function(){
$('#web').hover( function(){
$(this).css('background', '#000 url(space-image.png) center center fixed no-repeat');
}); // <-- you missed this, meaning 'end of hover function'
});
还有,
onMouseOver="document.getElementByName('body').style.backgroundColor = 'red';
目前,浏览器会认为onmouseover 函数在body 之前的" 处停止。浏览器会将" 和第二个" 之间的所有内容设置为onmouseover。那就是:
document.getElementByName(
这显然不是很有效。您需要将第一个和最后一个 " 更改为 '。这样,浏览器会将 's 之间的所有内容作为有效的 onmouseover 值。
【解决方案2】:
您是否考虑过完全使用 CSS3 伪类来做这件事?换句话说:
#web:hover {
background: #000 url(space-image.png) center center fixed no-repeat;
}
编辑:
您要更改整个页面的背景图片还是仅更改单个元素?如果是整个页面,那么您需要将 $('body') 替换为 $(this),因为 $(this) 只是指您在上一行中选择的 #web 元素。
【解决方案3】:
这可行:http://jsfiddle.net/gilly3/aBCqQ/
$(function(){
$("div").hover(function(){
$(this).css({backgroundImage: "url(http://farm2.static.flickr.com/1234/1324629526_1020726ce3_m.jpg)"});
},function(){
$(this).css({backgroundImage: ""});
});
});
对非 jQuery 代码的一些观察:
onMouseOver 指的是什么?您是否将该字符串分配给变量?元素的onmouseover 属性必须全部小写。
您必须使用\ 转义字符串中的引号。所以...("body")... 变成了...(\"body\")...。
没有getElementByName 方法。有一个getElementsByName(复数),但你真的给元素一个名称属性“body”吗?您可以通过以下方式获取 body 元素:document.body。
为什么要使用字符串,你应该使用函数:
myElement.onmouseover = function() {
document.body.style.backgroundColor = "red";
};
【解决方案4】:
$("p").hover(function() {
$("p").css("background-color", "yellow");
}, function() {
$("p").css("font-size", "25px");
});
以上示例包含如何使用悬停更改background-color 和font-size。