javascript - 在移动或桌面视口(viewport)中时 jQuery 触发函数

标签 javascript jquery

我的脚本遇到的问题是,它在加载时工作正常,但例如,如果您在移动 View (小于 500px)中开始并单击按钮,它会正确隐藏/显示 div 并阻止链接可点击。但是,如果您将屏幕大小调整为桌面,移动功能仍在运行,并在单击时显示 div 并阻止链接可单击。

如果您在桌面 View 中启动并转到移动设备,则反之亦然,桌面功能仍会在移动 View 中触发

有人知道我做错了什么吗?

https://jsfiddle.net/x2w3vp5n/1/

var fluid = function() {
  if ($(window).width() >= 500) {
    desktop();
  } else {
    mobile();
  }
};

// Fire on DOM ready
fluid();

// Fire upon resize
$(window).resize(fluid);

function desktop() {
  $('.container').on({
    mouseenter: function(e) {
      $(this).addClass('active');
    },
    mouseleave: function(e) {
      $(this).removeClass('active');
    }
  });
}

function mobile() {
  $('.btn').on('click', function(e) {
    var $this = $(this).closest('.container');
    e.preventDefault();
    e.stopPropagation();

    $this.toggleClass('active');

    return false;
  });
}

最佳答案

您需要“取消注册”页面首次加载时设置的处理程序。

您使用 $().on 附加的任何函数都将继续触发,直到您使用 $().off() 之类的东西取消附加它。

由于您的 mobiledesktop 函数绑定(bind)到 DOM 的不同部分,因此您只需删除每个函数顶部的相反函数的事件绑定(bind)即可:

var fluid = function() {
  if ($(window).width() >= 500) {
    desktop();
  } else {
    mobile();
  }
};

// Fire on DOM ready
fluid();

// Fire upon resize
$(window).resize(fluid);

function desktop() {
  //turn off mobile function attached to .btn
  $('.btn').off();
  $('.container').on({
    mouseenter: function(e) {
      $(this).addClass('active');
    },
    mouseleave: function(e) {
      $(this).removeClass('active');
    }
  });
}

function mobile() {
  //turn off desktop function attached to .container
  $('.container').off();
  $('.btn').on('click', function(e) {
    var $this = $(this).closest('.container');
    e.preventDefault();
    e.stopPropagation();

   $this.toggleClass('active');

    return false;
  });
}

https://jsfiddle.net/ebbyntq5/

关于javascript - 在移动或桌面视口(viewport)中时 jQuery 触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859392/

相关文章:

javascript - 如何更改我的 js 单击按钮以按住

javascript - 使用jquery记住浏览器刷新时剩余时间

javascript - 如何获取输入值并将其 append 到新元素?

jquery - 均衡元素高度功能不起作用

html - JQuery - 从其可滚动区域取消链接可拖动元素

javascript - 使用 React Router Dom 的 URL 路径级别

javascript - 使用preventDefault后,为什么我不能用jquery选中一个框?

javascript - 如何通过函数返回post结果?

javascript - 如果验证未通过如何不提交表单

javascript - 在移动版网站上使用 javascript 未添加 CSS 类