[英]Change CSS3 Background image on <p> hover
當我在某個段落上使用 hover 時,我正在嘗試使背景圖像(我使用 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';
和其他沒有運氣的人。
第一的,
$(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
function 停在"
之前的body
。瀏覽器會將"
和第二個"
之間的所有內容設置為onmouseover
。那就是:
document.getElementByName(
這顯然不太有效。 您需要將第一個和最后一個"
更改為'
。這樣,瀏覽器會將'
之間的所有內容作為有效的onmouseover
值。
您是否考慮過完全使用 CSS3 偽類來做到這一點? 換句話說:
#web:hover {
background: #000 url(space-image.png) center center fixed no-repeat;
}
編輯:
您想更改整個頁面的背景圖像還是僅更改單個元素? 如果是整個頁面,那么您需要將 $('body') 替換為 $(this),因為 $(this) 只是指您在上一行中選擇的 #web 元素。
$("p").hover(function() {
$("p").css("background-color", "yellow");
}, function() {
$("p").css("font-size", "25px");
});
上面的示例包含如何使用 hover 更改background-color
和font-size
。
這個作品: 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
。
為什么要使用字符串,應該使用 function:
myElement.onmouseover = function() {
document.body.style.backgroundColor = "red";
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.