2012-04-02 76 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中访问时将其用引号括起来