2012-04-02 78 views
1

我有以下HTML使用父的屬性:設置子元素ATTR使用jQuery

<ul id="clients-strip"> 
    <li> 
    <a href="http://example.com/case-studies/" data-colour="/images/made/assets/images/article-images/client-colour.png"> 
     <img src="/images/made/assets/images/article-images/client-grayscale.png" alt="Client" width="59" height="35"> 
    </a> 
    </li> 
    </ul> 

,需要與母公司「A」的元素「數據彩」基本上交換IMG SRC屬性時的「a」元素懸停(我想淡出舊的ATT,並在新太褪色)

我jQuery是不是太順利:(

$('ul#clients-strip li a').hover(function(){ 
     $(this.' img').attr('src', this.data-colour); 
    }); 

任何想法至於我做錯了什麼?那麼,是否有可能基本淡出一張圖像,並以我在這裏嘗試的方式淡入另一張圖像?

回答

1

你應該做的

$('ul#clients-strip li a').hover(function(){ 
    //get the child image and change the src 
    $('img', this).attr('src', $(this).data('colour')); 
}); 

如果你wan't返回到原來的SRC離開時,你可以做

var cacheSrc; 
$('ul#clients-strip li a').hover(function(){ 
    cacheSrc = $('img', this).attr('src'); 
    //get the child image and change the src 
    $('img', this).attr('src', $(this).data('colour')); 
}, 
function(){ 
    $('img', this).attr('src',cacheSrc); 
}); 
+1

尼古拉,你的工作很棒!你有什麼想法我可以讓他們淡入淡出每個過渡? – bjohnb 2012-04-02 13:51:23

+0

@bjohnb這很困難,你應該有兩個圖像,並隱藏()一個和fadeIn()其他,但你應該改變你的標記 – 2012-04-02 13:52:33

+0

這就是我最初嘗試,但由於某種原因,我無法深思是使所有圖像組合在一起。我認爲現在我可以繼續使用這兩種圖像方法了!再次感謝!! – bjohnb 2012-04-02 13:58:37

0

更換this.data色與$(本).attr ('數據顏色'),我認爲這應該工作。您也必須備份原始的src以在懸停後將其恢復。

1

我敢肯定, 「本」 上

$(this.' img').attr('src', this.data-colour); 

返回一個對象。

$(this).children('img').attr('src', this.data-colour); 

或也許

$(this).closests('img') 

或也許

$(this).children().eq(0) 

其中0是陣列中的對象的索引返回

檢查JQuery的嘗試api

+0

注意:.closest()查找祖先,而不是孩子。 – ezakto 2012-04-02 13:44:33

+0

謝謝,我忘了它。我不太喜歡它 – chepe263 2012-04-02 14:29:53

1

這個答案不使用JS我真的覺得你應該只是使用CSS Sliding門代替這種技術。您在鏈接上徘徊 - 我假設它是菜單的一部分 - 並且以該格式加載圖像只會導致瀏覽器在加載圖像時掛起一秒。

我推薦這裏描述的技術:http://line25.com/tutorials/how-to-create-a-css-menu-using-image-sprites,基本上只是設置一個類和背景精靈到整個菜單,並改變懸停的背景圖像位置。這將加載更快,並防止圖像加載時的閃爍。

0
$('ul#clients-strip li a').hover(function(){ 
var source = $(this).data('colour'); 
var $a = $(this); 
$('img',this).toggleFade(function(){ 
    $a.data('colour',$(this).attr('src')); 
    $(this).attr('src',source); 
    $a.toggleFade(); 
}); 
}); 
+0

我推薦@mikevoermans解決方案,因爲數據顏色img不會在頁面加載時加載到瀏覽器緩存中,並且會導致延遲。您可以通過淡入淡出暫停「掛起」。 – DefyGravity 2012-04-02 13:50:54

0

這應該這樣做,還沒有測試過,但想法是存在的。

$('#clients-strip li a').hover(function(){ 
    var a = $(this); 
    $(this).find('img').fadeOut(500, function(){ 
     $(this).attr('src', a.attr('data-colour')).fadeIn(500); 
    }); 
}); 
0

您的屬性名稱不可訪問e。摹this.data-colour將通過JavaScript訪問時,被翻譯成數學表達式:

因此,你應該使用$(this).attr('data-colour')代替this.data-colour

記住-破折號實際上是負操作

$('ul#clients-strip li a').hover(function(){ 
      var toggleWith= $(this).attr('data-colour'); 
      $(this+' img').attr('src', toggleWith); 
     }); 

雖然- dashvalid html name attribute當從javascript中訪問時將其用引號括起來