How to unbind() .hover() but not .click()?

笑着哭i 提交于 2019-12-05 20:10:26

Might be easier to selectively apply the hover, rather than try to remove it later. You can use window.matchMedia and only apply your script if the browser has a screen size that implies a desktop browser (or a largish tablet):

if (window.matchMedia("(min-width: 800px)").matches) {
    /* the view port is at least 800 pixels wide */
    $('.dropdown').on({
        mouseenter: function () {
            //stuff to do on mouse enter
        },
        mouseleave: function () {
            //stuff to do on mouse leave
        }
    });
}
else{
    $('.dropdown').off('mouseenter, mouseleave');
}

Since it's not 100% supported, you'd want to add a polyfill for those browsers without native support: https://github.com/paulirish/matchMedia.js/

If you're using Moderizr, that polyfill is included in that library already, so you're good-to-go.

I still don't understand how you intend to "dismiss" the dropdown-menu once it is displayed upon mousing over the dropdown element partly because there's not enough code in your question, but that's sort of irrelevant to this answer.

I think a much easier way to approach the mousenter event handling portion is not by using off()/on() to unbind/bind events at a specific breakpoints, but rather to do just do a simple check when the event is triggered. In other words, something like this:

$('.dropdown').on('mouseenter', function() {
    if($('.navbar-toggle').css('display') == 'none') {
       $(this).children('.dropdown-menu').show();
    };
});

$('.dropdown-menu').on('click', function() {
    $(this).hide();
});

Here's a working fiddle: http://jsfiddle.net/jme11/g9JJk/

Basically, in the mouseenter event I'm checking if the menu toggle is displayed, but you can check window.width() at that point instead if you prefer. In my mind, the toggle element's display value is easier to follow and it also ensures that if you change your media query breakpoints for the "collapsed" menu, the code will remain in sync without having to update the hardcoded values (e.g. 768px).

The on click to dismiss the menu doesn't need a check, as it has no detrimental effects that I can see when triggered on the "collapsed" menu dropdown.

I still don't like this from a UX perspective. I would much rather have to click to open a menu than click to close a menu that's being opened on a hover event, but maybe you have some magic plan for some other way of triggering the hide method. Maybe you are planning to register a mousemove event that checks if the mouse is anywhere within the bounds of the .dropdown + 50px + .dropdown-menu or something like that... I would really like to know how you intend to do this (curiosity is sort of killing me). Maybe you can update your code to show the final result.

EDIT: Thanks for posting your solution!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!