简体   繁体   English

在特定视口宽度以下禁用事件处理程序

[英]Disable event handler below a certain viewport width

I'm currently trying to disable a script when the window width is less than 700px. 我目前正在尝试在窗口宽度小于700px时禁用脚本。 I have looked at the advice on other posts but nothing has work as of yet. 我看过其他帖子上的建议,但到目前为止还没有任何工作。

window.onresize = function () {
    if(window.innerWidth < 700) {
        $(window).bind('scroll', function() {
            if ($(window).scrollTop() > 100) {
                $('#projectinfo').hide();
            } else {
                $('#projectinfo').show();
            }
        });
    }
}

The problem is that you never unbind your event handler once it has been attached to the window. 问题在于,一旦将事件处理程序附加到窗口,就永远不会解除绑定 I suggest you also do not bind the scroll event handler every time the window.resize event triggers, because this is an extremely costly event performance-wise. 我建议您也不要在每次 window.resize事件触发时绑定滚动事件处理程序,因为这是非常昂贵的事件性能。 Also, you keep rebinding an already existing handler which, if it works at all, is still horribly bad practice. 同样,您将重新绑定一个已经存在的处理程序,如果它可以工作的话,仍然是非常糟糕的做法。

What you probably really want is to decide on document.ready whether to attach the scroll handler or not. 您可能真正想要的是决定document.ready是否附加滚动处理程序。 If the resize use case is really relevant (web users don't usually ever resize their browser window while viewing a specific page, it's just what web frontend developers keep doing to check the responsiveness of their work), first test if your scroll handler is currently attached to window and only add it if it is not and (&&) your window.innerWidth >= 700 . 如果调整大小的用例确实相关(Web用户通常查看特定页面通常不调整浏览器窗口的大小,这只是Web前端开发人员一直在检查其工作的响应性),请首先测试您的滚动处理程序是否当前附加到window并且只有在未添加 (&&)您的window.innerWidth >= 700 ,才添加它。 Otherwise, check again if the scroll handler exist, and unbind it in case it exists and window.innerWidth < 700 . 否则,请再次检查滚动处理程序是否存在,并在其存在并且 window.innerWidth < 700情况下解除绑定。

http://api.jquery.com/unbind/ http://api.jquery.com/unbind/

Also, please note that you can name events when binding by using the event.name syntax when declaring the binding. 另外,请注意,您可以在声明绑定时使用event.name语法来命名事件。 Find this in the jQuery docs herefor: 在此处的jQuery文档中找到此内容:

Using Namespaces 使用命名空间

Instead of maintaining references to handlers in order to unbind them, we can namespace the events and use this capability to narrow the scope of our unbinding actions. 代替维护对处理程序的引用以解除绑定,我们可以为事件命名空间并使用此功能来缩小我们的解除绑定操作的范围。 As shown in the discussion for the .bind() method, namespaces are defined by using a period ( . ) character when binding a handler: 如对.bind()方法的讨论所示,在绑定处理程序时,使用句点( . )字符定义名称空间:

 $("#foo").bind("click.myEvents", handler ); 

When a handler is bound in this fashion, we can still unbind it the normal way: 当处理程序以这种方式绑定时,我们仍然可以按常规方式将其解除绑定:

 $("#foo").unbind("click"); 

However, if we want to avoid affecting other handlers, we can be more specific: 但是,如果我们想避免影响其他处理程序,则可以更加具体:

 $("#foo").unbind("click.myEvent"); 

We can also unbind all of the handlers in a namespace, regardless of event type: 我们也可以取消绑定命名空间中的所有处理程序,而与事件类型无关:

 $("#foo").unbind(".myEvent"); 

It is particularly useful to attach namespaces to event bindings when we are developing plug-ins or otherwise writing code that may interact with other event-handling code in the future. 当我们开发插件或以其他方式编写将来可能与其他事件处理代码交互的代码时,将名称空间附加到事件绑定上特别有用。

unbind and bind perhaps unbindbind

var $w = $(window);

function scrollHandler(e) {
  $('#projectinfo').toggle($w.scrollTop() > 100);
}

$(window).resize(function (e) {
  $w.width() < 700 ? $w.bind('scroll', scrollHandler) : $w.unbind('scroll', scrollHandler);
});

Obviously this needs some optimization improvements, but it's just to show the basic idea. 显然,这需要进行一些优化改进,但这只是为了展示基本思想。

Do not use bind (it is deprecated), use on (and off ). 不要使用bind (已弃用),请使用on (和off )。 Some other suggestions in comments 评论中的其他建议

(function ($, w, d) {
    $(function () {
        var $projectinfo = $('#projectinfo');
        var $w = $(w);
        var useScroll;

        function useScroll() {
            if ($w.scrollTop() > 100) {
                // Don't use hide() and show(), add or remove a class, instead
                $projectinfo.addClass('hidden');
            } else {
                $projectinfo.removeClass('hidden');
            }
        });

        function checkWindowWidth() {
            var useScrollTop = $w.width() < 700;
            if (useScrollTop) { 
                $w.on('scroll', useScroll);
            } else {
                $w.off('scroll', useScroll);
            }
        };

        // On resize, just check once the viewport width
        $w.on('resize', function () {
            // You should use a 'debounce' function, for this
            checkWindowWidth();
        });


    })
})(jQuery, window, document);

See this: debounce , bind vs on 看到这个: 去抖动绑定vs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM