如何取消/删除功能(更改屏幕尺寸时)- Jquery

问题描述 投票:0回答:1

如何根据屏幕尺寸取消/删除功能? 目前,我的功能从纵向转移到横向(反之亦然) .
那么可以删除/取消某个功能吗?如果不是我还应该做什么?

Jsfiddle 用于演示和更多说明:https://jsfiddle.net/tmcoqLgu/67/

Jquery 代码:

  var width = [0, 575];
  var height = [0, 575];

  function ScreenTrigger() {
    if (window.innerWidth >= width[0] && window.innerWidth < width[1]) {
      $('.display').addClass("portrait");
      $('.display').removeClass("landscape");
      if ($('.display').hasClass("portrait")) {

        // This function will carry over to both screen sizes once you resize the screen.
        $("#btn").click(function() {
          alert("This is an alert message!");
        });

      };
    } else if (window.innerHeight >= height[0] && window.innerHeight < height[1]) {
      $('.display').addClass("landscape");
      $('.display').removeClass("portrait");
      if ($('.display').hasClass("landscape")) {
        //
        /* 

            Delete Alert Function Here

        */
        //
      };
    } else {
      $('.display').removeClass("landscape");
      $('.display').removeClass("portrait");
    }
  };
  window.onresize = ScreenTrigger;
  ScreenTrigger();

在两种屏幕尺寸中添加双重功能(相同的功能,但具有不同的内容以相互抵消),对我来说不起作用,因为我的目标 DIV 在两种屏幕尺寸中使用不同。

使用

if ($('.display').hasClass("portrait"))
来环绕函数,取消 1 或另一个,也不起作用。

javascript html jquery function window
1个回答
0
投票

您正在使用 jQuery 的

click
函数。此方法会触发元素上的单击事件,单击事件完成后,它将运行您提供的回调函数。我相信您可能会尝试向元素添加事件侦听器,这可以使用
on
方法来实现。

更换

$("#btn").click(function() {
    alert("This is an alert message!");
});

$("#btn").on("click", function() {
    alert("This is an alert message!");
});

现在,当用户单击按钮时,回调将运行。

其次,通过“删除函数”,我假设您想要删除事件侦听器。您可以使用 jQuery 的

off
方法来完成此操作。

function triggerAlert() {
    alert("This is an alert message!");
}

// the button now alerts when the user clicks it
$("#btn").on("click", triggerAlert);

// the button no longer alerts when the user clicks it
$("#btn").off("click", triggerAlert);

需要注意的一件重要事情是,您必须将要删除的确切函数传递给

off
方法,这意味着您必须在外部存储该函数,而不是将其内联到 .on 方法调用中。

© www.soinside.com 2019 - 2024. All rights reserved.