Home  >  Q&A  >  body text

javascript - 怎样用js实现一个元素的 hide->show->hide->show 这么循环的动画?

RT,本来我尝试过用css3来写动画,但是效果是渐变的而我希望是不拖泥带水的闪动;
js的话尝试了下面的写法,不过一点儿效果也没有,无论是放在(document).ready 中还是放在外面。。。

function rc(){
    setTimeout("$('.car-rc').hide()",1000);
    setTimeout("$('.car-rc').show()",1000);
    }
setInterval("rc()",1000);

所以提问向大家请教,谢谢。

高洛峰高洛峰2749 days ago734

reply all(9)I'll reply

  • 阿神

    阿神2017-04-10 14:33:15

    var flag = true;
    setInverval(function(){
        (flag = !flag) ? show() : hide();
    },1000);
    

    reply
    0
  • 阿神

    阿神2017-04-10 14:33:15

    来个CSS版的:

    http://jsfiddle.net/v8Uc8/2/

    reply
    0
  • 阿神

    阿神2017-04-10 14:33:15

        var e = document.getElementById("Your ID");
        function hide() {
                        // Your Code
            e.style.cssText = "display: none";
        }
        function show() {
                        // Your Code
            e.style.cssText = "display: inline";
        }
    
        setInterval(hide, 1000);
        setInterval(show, 2000);
    

    reply
    0
  • PHPz

    PHPz2017-04-10 14:33:15

    你要的就是一个闪烁的效果吧!?

    $('.XX')
    .fadeOut(100)
    .fadeIn(100)
    .fadeOut(100)
    .fadeIn(100);

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 14:33:15

    setInterval(function(){
        $('#xx').toggle();
    },1000)
    

    你没效果的原因是同时设置 setTimeout,而且时长也是一样的,差不多同时隐藏同时显示了,在很微小的时间内肉眼看不清变化

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 14:33:15

    你这里的代码首先是两个setTimeout()并列而且时间也一样。题主那种作法执行太快了,基本没效果。

    我猜题主要的效果应该是hide之后1秒再show的意思,看了一下jquery的api>>
    大概的作法 可以是hide完之后再settimeout,即回调里执行timeout。

    $(document).ready(function(){
            var btn = $('#btn');
            //console.log("d");
            function show(){
                   setTimeout(function(){btn.show();},1000)
            }
            function rc(){
                setTimeout(function(){
                             btn.hide(10,show);
                             console.log("hided?");
                         },1000);
            }
            setInterval(function(){rc();},1000);
        });
    

    不过,闪烁估计不是我这种作法。我只是做个开头表示一下。:-)

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:33:15

    用gif图片

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:33:15

    http://jsfiddle.net/htbNt/

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 14:33:15

    jquery中实现了Deferred对象,你这个问题就好办多了。
    因为只是针对一个元素,动画积累的问题,可以交给stop来控制(若是包括了其它动画,这里就还需要全局动画变量来控制)。
    而动画的先后过程控制,请用then

    $(function(){
        var fadeInAnimate=function(){
            return $(this).fadeIn(1000).promise();
        };
        var fadeOutAnimate=function(){
            return $(this).fadeOut(1000).promise();
        };
        $('.block').promise().then(fadeOutAnimate).then(fadeInAnimate).then(fadeOutAnimate).then(fadeInAnimate);
    });
    

    reply
    0
  • Cancelreply