Cross-fade for inline text elements with jQuery

坚强是说给别人听的谎言 提交于 2019-12-11 03:49:47

问题


I am looking for a way to properly animate/crossfade inline anchor elements with jQuery. There are several solutions out there for block elements, but nothing so far for inline-elements.

My alternative text for each individual word comes from an attribute within the element:

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

But if I try to fadeout, replace the text and fade in, like here:

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

I am not getting the cross-fade effect that I would like, but a fadeout followed by a fadein, as you can see in this demo.

I'd be very grateful for any tips you might have.


回答1:


Here's what i came up with:

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

You may have to adjust this to work with different line-heights, though.



来源:https://stackoverflow.com/questions/11384834/cross-fade-for-inline-text-elements-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!