淡出后延迟$ link.text(jquery)

时间:2013-07-01 18:09:22

标签: jquery delay fadeout slidetoggle

我想在.content淡出后显示第二个[更多]。 jsfiddle

HTML

<div>
    <span class="heading">This is the beginning of the sentence. </span>
    <span class="content">This is the end of the sentence. </span>
</div>

CSS

.heading {
    cursor: pointer;
}

JS

$(document).ready(function () {
    $('.content').after('<a href="#" class="toggle-link">[Read More]</a>');
    $(".content").hide();
    $('.toggle-link').click(function (e) {
        e.preventDefault();
        var $link = $(this);

        if ($link.data('expanded') == true) {
            $link.data('expanded', false);
            $link.text('[Read More]');            
        } else {
            $link.data('expanded', true);
            $link.text('[Close]');
        }

        $link.prev(".content").fadeToggle(1000);
    });    

});

3 个答案:

答案 0 :(得分:1)

将它放在fadeToggle回调中,以便在动画完成后显示。另外,如果您要存储扩展只是为了交换文本值,您不需要它。您可以使用.text()回调函数来返回基于当前文本的值。

$(document).ready(function () {
    $('.content').after('<a href="#" class="toggle-link">[Read More]</a>');
    $(".content").hide();

    $('.toggle-link').click(function (e) {
        e.preventDefault();
        var $link = $(this);
        $link.prev(".content").fadeToggle(1000, function () { //Do it here
            var isExpanded = $link.data('expanded'); //Get the expanded value
            $link.text(function (_, text) { //use .text() function to switch value
                return text == "[Read More]" ? "[Close]" : "[Read More]"; 
            });
            $link.data('expanded', !isExpanded); //Dont need this if you are using this only  for expand collapse text switching.

        });
    });

});

<强> Demo

答案 1 :(得分:1)

在fadeToggle()的回调函数之后添加所有相反的代码,以确保它完成..

试试这个

$(document).ready(function () {
$('.content').after('<a href="#" class="toggle-link">[Read More]</a>');
$(".content").hide();
$('.toggle-link').click(function (e) {
    e.preventDefault();
   var $link = $(this);
    $link.text('');  //<---here empty the text so the animation is clear
    $link.prev(".content").fadeToggle(1000,function(){



    if ($link.data('expanded') == true) {
        $link.data('expanded', false);
        $link.text('[Read More]');            
    } else {
        $link.data('expanded', true);
        $link.text('[Close]');
    }
    });
});    

});

fiddle here

答案 2 :(得分:0)

How about
$link.prev(".content").fadeToggle(1000, function(){
    //code to fade read more link in
});