简体   繁体   English

当屏幕宽度小于或大于时阻止运行javascript

[英]Prevent javascript from running when screen width is less or more than

I have 2 menus that are contained on the same page but in different locations. 我有2个菜单,它们包含在同一页面上,但位置不同。 One appears when I have screen width > 555px and the parent div is set as display:none when under this size. 当我的屏幕宽度> 555px并且父div设置为display:none时,出现一个。 The other is display:none when 555px or over and shows when less than 555px. 另一个是display:none:555像素或更高时不显示,小于555px时显示。 Its the same menu but one is on a different section of the page for mobile/smaller screens. 它具有相同的菜单,但在移动/较小屏幕的页面的不同部分中。

I have javascript on some of the drop down options on the menu and it works for the first menu but not the second, I believe because the js is still attempting to run for the display:none so on the second attempt (on the small screens) it doesn't work. 我在菜单上的某些下拉选项上使用了javascript,它适用于第一个菜单,但不适用于第二个菜单,我相信是因为js仍在尝试为显示运行:第二次尝试都没有(在小屏幕上) )不起作用。

I'm probably over-complicating what needs to be done but I've attempted to create some code that uses js to create the div that contains the menu code for desktop and mobile and removes them when it shouldn't... so a media query version controlled by js rather than css that rather than hide the div and content will actually make it not be present. 我可能使需要完成的工作过于复杂,但是我尝试创建一些使用js的代码来创建div,该div包含用于台式机和移动设备的菜单代码,并在不应该的时候将其删除...因此由js控制的媒体查询版本,而不是由CSS控制,而不是隐藏div,而内容实际上会使该查询不存在。

I'm a complete novice at javascript and have just attempted to adapt other code I've seen, basically all I want to do is when >555px browser width add and when it moves under remove then I can use the same code down the page to add/remove div id="y"... 我是javascript的完全新手,并且刚刚尝试适应我所看到的其他代码,基本上我要做的就是当> 555px浏览器宽度添加时,当它在remove下移动时,我可以在页面上使用相同的代码添加/删除div id =“ y” ...

function DynamicDiv() {
        var dynDiv = document.createElement("div");
        dynDiv.id = "search-holder1";
        dynDiv.innerHTML = "Created using JavaScript";
        document.body.appendChild(dynDiv);
    }

var elem = document.getElementById("search-holder1");

function myFunction(x) {
    if (x.matches) { // If media query matches

     DynamicDiv();

    } else {

        elem.parentNode.removeChild(elem);
    }
}

var x = window.matchMedia("(max-width: 555px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

Here is my way: 这是我的方式:

function chooseMenu() {
    var width = window.innerWidth;
    if (width > 555) {
        //Add your div
    else {
        //If div is in document then remove, and add mobile div
    }
}
window.onresize = chooseMenu;

You should probably do the same function at the beggining with an anonymous function too. 您可能应该在使用匿名函数开始时也执行相同的功能。

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

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