Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

css - Animating inline elements with jQuery

I am trying to show and hide an inline element (eg a span) using jQuery.

If I just use toggle(), it works as expected but if I use toggle("slow") to give it an animation, it turns the span into a block element and therefore inserts breaks.

Is animation possible with inline elements? I would prefer a smooth sliding if possible, rather than a fade in.

<script type="text/javascript">
    $(function(){
        $('.toggle').click(function() { $('.hide').toggle("slow") });
    });
</script>
<p>Hello <span class="hide">there</span> jquery</p>
<button class="toggle">Toggle</button>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

toggle() has a bunch of weird things with it, including hiding or transforming odd elements at times. here's a similar solution:

$('.toggle').click(function() {
  $('.hide').animate({
    'opacity' : 'toggle',
  });
});

edit: here's a way to add smooth sliding, with minimal extra HTML markup:

var hidepos = $('.hide').offset().left;
var slidepos = $('.slide').offset().left;

$('.toggle').click(function() {
    var goto = ($('.slide').offset().left < slidepos) ? slidepos : hidepos;

    $('.slide').css({
        'left' : $('.slide').offset().left,
        'position' : 'fixed',
    }).animate({
        'left' : goto,
    }, function() {
        $(this).css('position', 'static');
    });

    $('.hide').animate({
        'opacity' : 'toggle',
    });
});

html:

<p>Hello <span class="hide">there</span> <span class="slide">jquery</span></p>
<button class="toggle">Toggle</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...