2010-10-11 45 views
1

我需要能夠更改包含div中的背景圖像的位置,當我將鼠標懸停在該div內的鏈接上時。當我將鼠標懸停在鏈接上時,如何獲取div背景以更改 - 使用jQuery?

這是page:它是右中間的兩個藍色播放按鈕。

我以前工作過,但它壞了,我無法讓它正常工作。

下面是HTML:

<div class="h-video"> 
<p><a class="play-video" href="#flashArea3">Secondary headline goes here to say something you want. This needs to grab their attention.</a></p> 
</div> 

這裏是jQuery的:

$(".h-video").hover(function() { 
$(this).closest("div").css({ 'background-position': 'top center' }); 
    }, function() { 
$(this).closest("div").css({ 'background-position': 'bottom center' }); 
}); 

我將不勝感激的任何援助。

謝謝。

回答

4

爲什麼使用javascript?儘管IE6不支持<div>元素,但您可以單獨在CSS中執行此操作。

例子:http://jsfiddle.net/yr4yH/1/

CSS從上面的例子:

.h-video { 
    width: 461px; 
    height: 67px; 
    background-image: url("http://www.theideapeople.com/projectpath/ideapeople-new/_images/btn_video-home.png"); 
    background-position: bottom center; 
    background-repeat: no-repeat 
} 

.h-video:hover { 
    background-position: top center; 
}​ 

如果您需要支持IE6,我敢肯定,你可以重做你的佈局使.h-video<a>元素代替的<div>

+0

事實證明,這是對這種情況最有效的解決方案。謝謝。 – fmz 2010-10-11 16:27:14

+0

@fmz - 不客氣。 :O) – user113716 2010-10-11 16:35:15

0

我會給這個解決方案留下一個單獨的答案,但我仍然會對use CSS instead of javascript說。

在加載元素之前,您的代碼將指定處理程序與.hover()一起運行。否則你的代碼是正確的。

下面的代碼示例用$(function() { ... });這是一個jQuery's .ready() method的快捷方式包裝您的代碼,它確保文檔在您的代碼運行之前加載。

// Wrap your code like this so it doesn't run until the DOM is ready 
$(function() { 
    $(".h-video").hover(function() { 
    $(this).closest("div").css({ 'background-position': 'top center' }); 
     }, function() { 
    $(this).closest("div").css({ 'background-position': 'bottom center' }); 
    }); 
}); 

而且,jQuery's .closest() method在此沒有必要,但它也沒有破壞。不妨將它刪除。

0

夫婦的注意事項:

  1. 你的位置顛倒:「中心頂」不「頂中心」和「中心底部」而不是「底部中心」參考:http://www.w3schools.com/css/pr_background-position.asp

  2. 使用addClass和RemoveClass。不要在線設置樣式。使用它就像docs.jquery.com上的示例一樣。

  3. 如果您不需要IE支持,請使用CSS聲明w/o javascript。

相關問題