jQuery event to trigger action when a div is made visible

后端 未结 22 2226
你的背包
你的背包 2020-11-22 12:03

I\'m using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.

Is it possible to attach some sort of \"isvisible\" even

22条回答
  •  有刺的猬
    2020-11-22 12:30

    my solution:

    ; (function ($) {
    $.each([ "toggle", "show", "hide" ], function( i, name ) {
        var cssFn = $.fn[ name ];
        $.fn[ name ] = function( speed, easing, callback ) {
            if(speed == null || typeof speed === "boolean"){
                var ret=cssFn.apply( this, arguments )
                $.fn.triggerVisibleEvent.apply(this,arguments)
                return ret
            }else{
                var that=this
                var new_callback=function(){
                    callback.call(this)
                    $.fn.triggerVisibleEvent.apply(that,arguments)
                }
                var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
                return ret
            }
        };
    });
    
    $.fn.triggerVisibleEvent=function(){
        this.each(function(){
            if($(this).is(':visible')){
                $(this).trigger('visible')
                $(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
            }
        })
    }
    })(jQuery);
    

    example usage:

    if(!$info_center.is(':visible')){
        $info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
    }else{
        processMoreLessButton()
    }
    
    function processMoreLessButton(){
    //some logic
    }
    

提交回复
热议问题