简体   繁体   English

使HTML元素基于文档宽度

[英]Make HTML element based off of document width

I'm trying to add a button for a mobile menu when the document width is less then 470. 当文档宽度小于470时,我正在尝试为移动菜单添加按钮。

It does it when the page loads initially, but when I mess with the width of the actual document on my browser it does not change alongside the document. 最初加载页面时会执行此操作,但是当我在浏览器中更改实际文档的宽度时,它不会随文档一起改变。 How do I achieve this? 我该如何实现?

Button should appear when width is less then 470 and go away when page width is greater then 470, basically. 宽度小于470时应该出现按钮,而页面宽度大于470时应该消失。

Here is my code. 这是我的代码。

        var width = $(document).width();
        if (width < 470) {
            $("<button id='menu'>Menu</button>").insertAfter("#navigation a img");
        } else {
            $("<button id='menu'></button>").hide();
        }

Bind the function/checks to a resize method on the window: 将函数/检查绑定到窗口上的resize方法:

$(window).resize(
    function(){
        /* do stuff in here */
    });

Simple proof-of-concept . 简单的概念证明

Check width of document every time window size change. 每次窗口大小更改时都要检查文档宽度。

function onresize(){
   var width = $(document).width();
   if (width < 470) {
        if($("#menu").length){
               $("#menu").show();
         }
         else{
                $("<button id='menu'>Menu</button>").insertAfter("#navigation a img");
         }
    } else {
        $("#menu").hide();
    }
}

onresize()//first call
$(window).resize(onresize);

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

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