【问题标题】:How to perform: onClick Javascript, hide a div with transition effect如何执行:onClick Javascript,隐藏带有过渡效果的 div
【发布时间】:2013-08-03 17:50:38
【问题描述】:

这是一个与另一个成员之前的问题相关的问题,可以找到here。

这是隐藏 div 的 Javascript 函数(这是对其他成员问题的回答):

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

HTML 是:

<div id='hideme'>
Warning: These are new products
<a href='#' class='close_notification' title='Click to Close'>
<img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" />
</a>
</div>

我对此的后续问题是:如何添加一个很酷的过渡效果?结果将是 div 'hideme' 会慢慢关闭。有解决办法吗?

非常感谢大家!将不胜感激!

注意:我是 Javascript 的菜鸟。 0-0

【问题讨论】:

  • 看看jQuery库,它提供了很多简单的方法来为事件添加漂亮的过渡效果。
  • 当然有:在&lt;div&gt;上设置overflow: hidden;,然后逐渐减小其height,最后设置display: none。或者只使用 jQuery,因为它已经做得很好了。
  • 老实说,谁会拒绝这个查询?正如我所说,我是一个菜鸟。山姆 - 谢谢,我会试着调查一下。 @Joker_vD - 我该怎么做?谢谢!

标签: javascript onclick


【解决方案1】:
$("#"+el).fadeOut(500);//el must be the id of the element

【讨论】:

  • 我试过这个,但它不起作用。或者,也许,我做错了? function hide(obj) {var el = document.getElementById(obj);el.style.display = 'none';$("#"+hideme).fadeOut(500);}谢谢。
【解决方案2】:

如果你使用的是 jQuery

function hide() {
    $(this).parent().fadeOut();
}

由于这是由事件触发的,因此“this”变量将被设置为它来自的元素,因为您希望父元素在单击时消失,这将起到作用

编辑:为此,您可能必须使用 HTML 以及需要多少 $(this).parent().parent()...,但这是最好的方法,然后您不需要传递 ID

编辑 2:所以 .parent() 选择包含所选元素的元素,所以在这种情况下 $(this) 指的是被点击的按钮,因为那是点击事件的来源。

所以 $(this).parent() 指的是容器元素,在这种情况下是 a 元素,因此 $(this).parent().parent() 指的是 div 元素想躲起来。

所以你可以给图像一个“可关闭”类,然后执行以下操作

$('.closable').click(function() {
    $(this).parent().parent().fadeOut();
}

这意味着每当您单击具有可关闭类的东西时,它会在 DOM 树上向上移动两个元素(使用.parent().parent()),然后将其淡出。

这将允许您从图像中删除点击事件,您只需将上面的处理程序放在 jQuery document.ready 函数中,如下所示:

$(document).ready(function() {
    //Click function here
});

【讨论】:

  • 山姆。谢谢。我不知道你说的$(this).parent().parent()... 是什么意思:(对不起...
【解决方案3】:

一个流行的选择是JQuery UI's effect method。 有了这个,你可以编写一些非常简单的 Javascript 来以时尚的方式隐藏你的 div,例如:

function hide(obj) {

   $(obj).effect("scale");

}

编辑: 这是一个例子jsFiddle

【讨论】:

  • 嗨@FLClover。谢谢。但是,我该怎么做呢? :)
  • 更新了我原来的答案。
【解决方案4】:

使用jQuery做过渡效果:

$(function(){
    $("a.close_notification").click(function(e){
        e.preventDefault();
        // stop other animations and hide, 500 milliseconds
        // you can use the function fadeOut for that too
        $("#hideme").stop().hide(500);

    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 2017-10-18
    • 2011-03-11
    • 2011-07-27
    • 2018-09-18
    • 2018-09-06
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多