【问题标题】:Cross-fade for inline text elements with jQuery使用 jQuery 对内联文本元素进行淡入淡出
【发布时间】:2012-07-08 16:41:53
【问题描述】:

我正在寻找一种使用 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 中看到的那样。

如果您有任何建议,我将不胜感激。

【问题讨论】:

  • 你需要两个元素来交叉淡入淡出。你不能在一个元素和它自己之间交叉淡入淡出,你当然不能在你交叉淡入淡出的时候让元素同时包含两个词。

标签: jquery jquery-ui text jquery-effects css


【解决方案1】:

这是我想出的:

$('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-heights。

【讨论】:

  • 我将它抽象为它自己的函数,它接受一个元素并作为参数复制,我唯一需要做的改变就是用包含的 div 选择器替换“body”。谢谢!
猜你喜欢
  • 2015-08-08
  • 1970-01-01
  • 2019-09-25
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
相关资源
最近更新 更多