【问题标题】:Will a scroll event also fire if the targeting element does not exist?如果目标元素不存在,滚动事件是否也会触发?
【发布时间】:2017-12-24 18:03:52
【问题描述】:

我有一个侧边栏作为子导航,并附加了一些自定义 javascript 以在用户向下滚动部分时突出显示其中的导航链接。我将此 javascript 包含在我的主 js 文件中。侧边栏未包含在每个页面上。对于性能我想知道,如果附加到此侧边栏的滚动事件也会在不包含侧边栏的站点上触发,或者在这些站点上忽略这段脚本?

        // waypoint for fixed sidebar
        $('.tg-desktop__accordionWrapper').waypoint(function (direction) {
            if (direction === 'down') {
                $(this.element).addClass('tg-accordion__sidebar--fixed');
            } else {
                $(this.element).removeClass('tg-accordion__sidebar--fixed');
            }
        });

        // cache the navigation links 
        var $navigationLinks = $('.tg-accordion__sidebarLink');
        // cache (in reversed order) the sections
        var $sections = $($(".tg-accordion__text").get().reverse());

        // map each section id to their corresponding navigation link
        var sectionIdTonavigationLink = {};
        $sections.each(function() {
            var id = $(this).attr('id');
            sectionIdTonavigationLink[id] = $('.tg-accordion__sidebarLink[href=#' + id + ']');
        });

        // throttle function, enforces a minimum time interval
        function throttle(fn, interval) {
            var lastCall, timeoutId;
            return function () {
                var now = new Date().getTime();
                if (lastCall && now < (lastCall + interval) ) {
                    // if we are inside the interval we wait
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(function () {
                        lastCall = now;
                        fn.call();
                    }, interval - (now - lastCall) );
                } else {
                    // otherwise, we directly call the function 
                    lastCall = now;
                    fn.call();
                }
            };
        }

        function highlightNavigation() {
            // get the current vertical position of the scroll bar
            var scrollPosition = $(window).scrollTop();

            // iterate the sections
            $sections.each(function() {
                var currentSection = $(this);
                // get the position of the section
                var sectionTop = currentSection.offset().top;

                // if the user has scrolled over the top of the section  
                if (scrollPosition >= sectionTop) {
                    // get the section id
                    var id = currentSection.attr('id');
                    // get the corresponding navigation link
                    var $navigationLink = sectionIdTonavigationLink[id];
                    // if the link is not active
                    if (!$navigationLink.hasClass('active')) {
                        // remove .active class from all the links
                        $navigationLinks.removeClass('active');
                        // add .active class to the current link
                        $navigationLink.addClass('active');
                    }
                    // we have found our section, so we return false to exit the each loop
                    return false;
                }
            });
        }

        $(window).scroll( throttle(highlightNavigation,100) );

【问题讨论】:

    标签: jquery performance events scroll


    【解决方案1】:

    就目前而言,滚动处理程序是无条件附加的,因此是的,即使没有侧边栏,该处理程序也会触发。而且,很可能,由于 jQuery 的宽容性质,什么都不会抛出;但如果没有侧边栏,则不会发生任何预期的副作用。

    在没有侧边栏的情况下不附加滚动处理程序应该很简单。事实上,问题中的任何代码似乎都不需要在此类页面(或“网站”,如果您愿意)上。

    我希望是这样的:

    var $navigationLinks = $('.tg-accordion__sidebarLink');
    
    if( $navigationLinks.length > 0 ) {
        $('.tg-desktop__accordionWrapper').waypoint(function(direction) {
            ...
        });
    
        ...
        ...
        ...
    
        function throttle(fn, interval) {
            ...
        }
    
        function highlightNavigation() {
            ...
        }
    
        $(window).scroll( throttle(highlightNavigation, 100) );
    }
    

    当然,如果您有一个单页应用程序 (SPA),并且有些内容有边栏而有些没有,那么这种方法就行不通。您可以将滚动处理程序永久附加(在某些情况下执行 nada),或者您可以安排滚动处理程序附加/分离以同情内容。

    【讨论】:

    • 谢谢!让我开心,没有考虑功能的长度选项!我想这应该总是这样做,如果滚动或调整大小处理程序只是偶尔使用:-) 圣诞快乐@Roamer-1888
    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多