2012-07-08 27 views
2

我正在寻找一种方法来正确使用jQuery设置/ crossfade内联定位元素。对于块元素有几种解决方案,但是对于内联元素来说目前还没有解决方案。使用jQuery对内联文本元素进行交叉淡入淡出

我每个单词替代文本来自元素中的一个属性:

<a data-r="nerd">word</a>​ 

但是,如果我试图淡出,替换文本和淡入,喜欢这里:

jQuery(document).ready(function($) { 
$('a').click(function(index) { 
    $(this).fadeOut(500, function() { 
     $(this).text($(this).attr("data-r")); 
    }); 
    $(this).fadeIn(500); 
    }); 
});​ 

我没有得到我想要的淡入淡出效果,而是淡入淡出,如您在此demo中看到的那样。

我会非常感谢您可能有的任何提示。

+1

您需要_two_元素进行交叉淡入淡出。您不能在元素和_itself_之间交叉淡入淡出,并且您在交叉淡入淡出时肯定不能同时包含_both_个单词。 – lanzz 2012-07-08 16:45:17

回答

5

这就是我想出了:

$('a').click(function(index) { 
 
    var clone = $(this).clone(); 
 
    clone.css('position', 'absolute'); 
 
    clone.css('left', $(this).position().left); 
 
    clone.css('top', $(this).position().top); 
 
    $('body').append(clone); 
 

 
    $(this).hide(); 
 
    $(this).text($(this).attr("data-r")); 
 

 
    clone.fadeOut(500, function() { 
 
    clone.remove(); 
 
    }); 
 
    $(this).fadeIn(500); 
 
});
a { font-size: 60px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<p> 
 
    <a data-r="nerd">word</a><br> 
 
    <a data-r="dork">word</a> 
 
</p>

您可能需要调整这种不同line-height s到工作,虽然。

+0

非常感谢,很棒。 – Tench 2012-07-09 06:33:40

+0

我将它抽象为它自己的函数,它接受一个元素并将其作为参数复制,而我必须做的唯一更改是用包含的div选择器替换“body”。谢谢! – ashack 2013-04-10 14:13:19