简体   繁体   English

如何仅在移动设备上添加菜单图标?

[英]How can I add a menu-icon on mobile devices only?

How can I add a menu-icon when I scale a page down below 769px? 当我将页面缩小到769px以下时,如何添加菜单图标?

I added a button a one page site that I am developing in order to display the menu on mobile devices. 我在正在开发的一页网站上添加了一个按钮,以便在移动设备上显示菜单。

Used this in jquery: 在jQuery中使用了这个:

if($(window).width() < 769){
    $('html').append('<i class="fa fa-bars menu-icon" aria-hidden="true"></i>');
}

The menu shows up if initially start the site with a window of size below 769px..but if I load the page on a big screen and try to resize the window to a width below 769,the menu-icon does not show up immediately.Instead I have to refresh the page for it to appear. 如果最初使用小于769px的窗口启动站点,则会显示菜单,但是如果我将页面加载到大屏幕上并尝试将窗口调整为小于769px的宽度,则菜单图标不会立即显示。相反,我必须刷新页面才能显示它。

Thanks in advance 提前致谢

Because the script you run just runs once... on page load I guess. 因为您运行的脚本只运行一次,所以在页面加载时就可以了。 Why would it react on resizing the window? 为什么会对调整窗口大小做出反应? You dont specify that in your script. 您无需在脚本中指定。

Its far easier to just add the icon in the original html and display/ hide it with css media queries : 只需在原始html中添加图标并使用CSS媒体查询显示/隐藏它,就容易得多:

.menu-icon { display: none; }

@media (max-width: 768px) {
  .menu-icon { display: block; }
}

Its also possible to detect mobile devices via css , not just based on the window width. 还可以通过CSS而不是仅基于窗口宽度来检测移动设备

You have to put your code inside $(window).resize() like follows so that whenever page size gets modified; 您必须将代码放入$(window).resize() ,如下所示,以便每当页面大小被修改时; the handler will get invoked and you can run your logic accordingly: 处理程序将被调用,您可以相应地运行逻辑:

$('html').append('<i class="fa fa-bars menu-icon" aria-hidden="true"></i>'); //append the icon to html
$("i.fa-bars.menu-icon").hide(); //hide it initially

$(window).resize(function() {
    if($(window).width() < 769){
        $("i.fa-bars.menu-icon").show(); //show it on mobile view
    }
    else
    {
        $("i.fa-bars.menu-icon").hide(); //hide it on bigger screen
    }
}).trigger('resize');//firing the resize immediately

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

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