如何将元素附加到dom时对元素应用效果?

时间:2013-07-18 10:23:18

标签: jquery jquery-plugins

我正在使用以下jquery跳出效果:

(function($){

    /* The plugin extends the jQuery Core with four methods */

    /* Converting an element into a bounce box: */
    $.fn.bounceBox = function(){

        /*
            Applying some CSS rules that center the
            element in the middle of the page and
            move it above the view area of the browser.
        */

        this.css({
            top     : -this.outerHeight(),
            marginLeft  : -this.outerWidth()/2,
            position    : 'fixed',
            left        : '50%'
        });

        return this;
    }

    /* The boxShow method */
    $.fn.bounceBoxShow = function(){

        /* Starting a downward animation */

        this.stop().animate({top:0},{easing:'easeOutBounce'});
        this.data('bounceShown',true);
        return this;
    }

    /* The boxHide method */
    $.fn.bounceBoxHide = function(){

        /* Starting an upward animation */

        this.stop().animate({top:-this.outerHeight()});
        this.data('bounceShown',false);
        return this;
    }

    /* And the boxToggle method */
    $.fn.bounceBoxToggle = function(){

        /*
            Show or hide the bounceBox depending
            on the 'bounceShown' data variable
        */

        if(this.data('bounceShown'))
            this.bounceBoxHide();
        else
            this.bounceBoxShow();

        return this;
    }

})(jQuery);

在动态加载的以下动态div上:

<div id="growl">
    <span id="growl-title" class="growl-title"></span>
    <span id="growl-content" class="growl-content"></span>
</div>

目前效果如下:用户点击按钮然后回调javascript在服务器端完成后执行,以显示效果如下的div:

$('#growl').bounceBoxToggle(); 

但我有一个案例,从服务器端我显示这个div基于一个属性(div可能附加到dom作为ajax调用的结果),如下所示:

<c:if test="#{showGrowl==true}">
<div id="growl">
        <span id="growl-title" class="growl-title"></span>
        <span id="growl-content" class="growl-content"></span>
</div>
</c:if>

,我希望在这种情况下显示div自动应用反弹效果时,请告知如何执行此操作。

2 个答案:

答案 0 :(得分:0)

检查div是否存在:

$(function(){ /* onload */
    if($('#growl').length > 0)
      $('#growl').bounceBoxToggle(); 
});

答案 1 :(得分:0)

我无法完全理解,但是如果你需要和div块一起执行一些脚本,你可以在if条件中嵌入一个脚本块。因此,只要条件为真,脚本就会被执行。

<c:if test="#{showGrowl==true}">
    <div id="growl">
        <span id="growl-title" class="growl-title"></span>
        <span id="growl-content" class="growl-content"></span>
    </div>
    <script>
        $(function(){ // Making an onload function
            $('#growl').bounceBoxToggle();
        })
    </script>
</c:if>