简体   繁体   English

使用 Jquery 动画切换可见性

[英]Animate toggle visibility with Jquery

I am toggling my Div's with the following code, but cant figure out if and how to animate it.我正在使用以下代码切换我的 Div,但无法弄清楚是否以及如何对其进行动画处理。 Any help would be appreciated.任何帮助,将不胜感激。

The link:链接:

<a href="#" onclick="toggle_visibility('example'); return false;"></a>

The script:剧本:

<script>

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
</script>

You tagged but I don't see any.你标记了但我没有看到任何。 In pure JS you'll have too much trouble for achieving this.在纯 JS 中,您将很难实现这一点。

Try using toggle() :尝试使用toggle()

function toggle_visibility(id) {
    $("#" + id).toggle('slow');
}

Besides, I would suggest you a better use of jQuery:此外,我建议您更好地使用 jQuery:

<a href="#" data-toggle="example"></a>

The code above is using a data attribute which combinated with event binding could make you code much clearer:上面的代码使用了一个数据属性,结合事件绑定可以让你的代码更清晰:

$(document).ready(function()
{
    $('a[data-toggle]').on("click", function()
    {
        toggle_visibility($(this).data("toggle"));
    }
});

Now all your links with data-toggle have the same behaviour.现在所有带有data-toggle链接都具有相同的行为。

rolling with DontVoteMeDown's pattern:使用 DontVoteMeDown 的模式滚动:

function toggle_visibility(id) {
   $("#" + id).slideDown("slow"); /* replace this with any of the following */
}

or或者

$("#" + id).fadeIn(500);

or或者

$("#" + id).fadeOut(500);

For more complex animations you can use easing as well.对于更复杂的动画,您也可以使用缓动。 http://easings.net/ .animate( properties [, duration ] [, easing ] [, complete ] ) http://easings.net/ .animate( 属性 [, 持续时间 ] [,缓动] [, 完整 ] )

If you want to animate it you can use JQuery and do the following 如果要设置动画 ,可以使用JQuery并执行以下操作

function toggle_visibility(id) {
   var e = document.getElementById(id);
   e.slideToggle('fast');
}

More documentation on .slideToggle() can be found here: http://api.jquery.com/slidetoggle/ 有关.slideToggle()更多文档,可以在这里找到: http : .slideToggle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM