简体   繁体   English

如何根据屏幕的像素宽度使JavaScript函数“超限”?

[英]How do I make a JavaScript function “off limits” based on the pixel width of the screen?

I have seen a lot of stuff on how to trigger a function right when the screen width goes past the defined max or min value but for my purpose I do not want the function to happen immediately. 我已经看到了很多有关如何在屏幕宽度超过定义的最大值或最小值时立即触发功能的内容,但是出于我的目的,我不希望该功能立即发生。 Here is a snippet of a JS function from W3 schools as an example. 这是来自W3学校的JS函数的片段作为示例。

function myFunction() {
  var x = document.getElementById("myLinks");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

Lets say I only wanted to have "access" to this function if my screen width is 500 or less and if it is 501 or more than it will not be using this function. 可以说,如果我的屏幕宽度为500或更小,并且屏幕宽度为501或更大,则我只想“访问”此功能。 In my circumstance there will be no other function for when it is above the specified width it will be doing something else by default. 在我的情况下,将不会有其他功能,因为当它超过指定宽度时,默认情况下它将执行其他操作。 The JavaScript function that I need to happen would be is an onClick event that should only be able to happen if the screen is below the specified width. 我需要执行的JavaScript函数是一个onClick事件,该事件仅在屏幕小于指定宽度时才可以发生。

You can simply wrap the contents of the function in an if that checks the width of the page's viewport against the value you want (eg, 500 ), or just immediately return out of the function, which saves a couple of curly braces. 您可以简单地将函数的内容包装在if ,以对照所需的值(例如500 )检查页面视口的宽度,或者只是立即return该函数,这样可以节省几个花括号。

function myFunction() {
  if (window.innerWidth > 500) return;
  var x = document.getElementById("myLinks");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}

If you're trying to ensure the function isn't used incorrectly by other developers, you could instead throw an error, eg, 如果您要确保其他开发人员未正确使用该功能,则可以抛出一个错误,例如,

if (window.innerWidth > 500) throw new Error("This function should not be called on viewports smaller than 500px width!");

I'd stick to a @media rule here, and instead of setting style.display directly, add/remove a class. 我在这里坚持使用@media规则,而不是直接设置style.display ,而是添加/删除类。

JS: JS:

function myFunction() {
  document.getElementById("myLinks").classList.toggle("mobile_hidden");
}

CSS: CSS:

@media screen and (max-width: 500px) {
  .mobile_hidden {
    display: none;
  }
}

An additional benefit of this is that resizing the window will auto-hide the element if it has the class. 这样做的另一个好处是,如果窗口具有类,则调整窗口大小将自动隐藏该元素。

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

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