代码之家  ›  专栏  ›  技术社区  ›  ItFreak

无边距视口中可见的Javascript元素

  •  0
  • ItFreak  · 技术社区  · 7 年前

    实际JS:

    (function ($) {
            $.fn.visible = function (partial) {
    
                var $t = $(this),
                    $w = $(window),
                    viewTop = $w.scrollTop(),
                    viewBottom = viewTop + $w.height(),
                    _top = $t.offset().top,
                    _bottom = _top + $t.height(),
                    compareTop = partial === true ? _bottom : _top,
                    compareBottom = partial === true ? _top : _bottom;
    
                return compareBottom <= viewBottom && compareTop >= viewTop;
            };
        })(jQuery);
    
        var win = $(window);
    
        var allModifications = $(".animation-listener");
    
        //make all elements visible that are directly visible
        allModifications.each(function (i, el) {
            console.log("loaded js");
            var el = $(el);
            if (el.visible(true)) {
                el.find(".half-width-text").addClass("open");
            }
        });
    
        //make elements visible that get scrolled into the viewport
        win.scroll(function (event) {
            var current = 1;
            allModifications.each(function (i, el) {
                var el = $(el);
                if (el.visible(true)) {
                    el.addClass("animate");
                }
            });
        });
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Arfeo    7 年前

    而不是使用 height() 使用 outerHeight(true)

    http://api.jquery.com/outerheight/