根据屏幕大小隐藏和显示元素

时间:2022-11-11 11:48:06

I'm trying to make button that will hide and show menu when web page is being displayed on smaller screens. I want to keep the whole menu when the display is wider than 640px. I'm only allowed to use CSS and JavaScript.

我正在尝试制作在较小的屏幕上显示网页时隐藏和显示菜单的按钮。当显示宽度大于640px时,我想保留整个菜单。我只允许使用CSS和JavaScript。

Here is the JS function I wrote:

这是我写的JS函数:

var b = document.getElementById ("menu-button");
b.addEventListener("click", showMenu, false);
var i = 0;
function showMenu () {
    i++;
    if(i % 2 == 1)
        document.getElementById("menu").style.display = "block";
    else
        document.getElementById("menu").style.display = "none";
}

It is working when displaying the page on smaller screen.

在较小的屏幕上显示页面时它正在工作。

When I click the button to hide the menu (that changes "menu" display to none) and then increase the size of the page, my menu does not appear when the screen becomes larger than 640px.

当我单击按钮隐藏菜单(将“菜单”显示更改为无)然后增加页面大小时,当屏幕变得大于640px时,我的菜单不会出现。

This media media query does not do the job:

此媒体媒体查询不起作用:

@media screen and (min-width:640px) {
    #menu {
        display: block;
    }
}

5 个解决方案

#1


6  

You need to add !important to the CSS property, like:

您需要在CSS属性中添加!important,例如:

 #menu { display:block!important; } 

Your Javascript adds style attribute to the element, which has higher priority than any internal or external CSS styles, unless they "are" !important.

您的Javascript将样式属性添加到元素,该元素具有比任何内部或外部CSS样式更高的优先级,除非它们“是”!重要。

What you can also consider doing to avoid that is to toggle some CSS class in your Javascript instead of setting style attribute. This way you avoid using !important.

您还可以考虑做的是避免这种情况,在Javascript中切换一些CSS类而不是设置样式属性。这样你就可以避免使用!important。

#2


3  

I suggest to not set an elements style like that, toggle a class on the element is the recommended way

我建议不要设置这样的元素样式,在元素上切换类是推荐的方法

Side note, I also changed from id to class, which is also recommended

旁注,我也从id改为class,这也是推荐的

Also, specificity is the reason, pointed out already in comments/answers, why your code doesn't work, more to read here: https://developer.mozilla.org/en/docs/Web/CSS/Specificity

此外,特殊性是原因,在评论/答案中已经指出,为什么你的代码不起作用,更多内容在这里阅读:https://developer.mozilla.org/en/docs/Web/CSS/Specificity

var b = document.querySelector(".menu-button");
b.addEventListener("click", function(e) {
  document.querySelector(".menu").classList.toggle("show");
});
.menu {
  display: none;
}
.menu.show {
  display: block;
}


@media screen and (min-width:640px) {
    .menu {
        display: block;
    }
}
<div class="menu show">Hi, I'm a menu element</div>
<button class="menu-button">Show/Hide</button>

#3


1  

Connexo has pointed out the answer but an expansion may be of some use to you and others who come here in the future.

Connexo已经指出了答案,但扩展可能会对您和将来来到这里的其他人有所帮助。

The 'style' of an HTML element can be set in at least 3 places. The browser will have to decide which should win should there be a *. The rules used are called 'specificity'. There is a good article on this topic here https://css-tricks.com/specifics-on-css-specificity/ if you want a fuller explanation.

HTML元素的“样式”可以设置在至少3个位置。如果发生冲突,浏览器必须决定哪个应该赢。使用的规则称为“特异性”。如果您想要更全面的解释,请在https://css-tricks.com/specifics-on-css-specificity/上找到关于此主题的好文章。

Roughly, any styling defined in the initial HTML 'style' attribute is most powerful so this will win in over a CSS file rule. Importantly, setting the style as you have done in your use case, operates on the HTML style attribute.

粗略地说,在初始HTML“样式”属性中定义的任何样式都是最强大的,因此这将胜过CSS文件规则。重要的是,在用例中设置样式,操作HTML样式属性。

Therefore, your CSS is being overruled by the style attribute setting in your code.

因此,您的CSS被代码中的样式属性设置所取代。

For a pure JS solution you could look at adding a listener to the window onResize event. If you do research that approach please be aware that in some browsers the event fires for every pixel of the size change, so look for a solution that takes that into consideration like this one otherwise the function will be triggered multiple times and may reduce the joy you bring to your users.

对于纯JS解决方案,您可以考虑向窗口onResize事件添加一个监听器。如果您研究这种方法请注意,在某些浏览器中,事件会触发尺寸变化的每个像素,因此请寻找一个考虑到这一点的解决方案,否则该功能将被多次触发并可能降低喜悦你带给你的用户。

#4


0  

As other comments suggested, you are trying different things in your code. I recommend a css solution, you can look into what most grids use to style their media queries to show / hide elements when browserwindow is being resized or the monitorsize becomes smaller.

正如其他评论建议的那样,您在代码中尝试了不同的东西。我建议使用css解决方案,您可以查看大多数网格用于设置其媒体查询的样式,以便在调整浏览器窗口大小或监视器缩小时显示/隐藏元素。

A very cool, light-weight grid is called simplegrid.

一个非常酷,轻量级的网格称为简单网格。

https://github.com/ThisIsDallas/Simple-Grid/blob/master/simplegrid.css

at line 177 the media query for 'handheld' devices start. So for instance adding this to your HTML document:

在第177行,“手持式”设备的媒体查询开始。因此,例如将其添加到HTML文档中:

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://github.com/ThisIsDallas/Simple-Grid/blob/master/simplegrid.css">
</head>
<body>
<button class="hide-on-mobile">MyButton</button>
</body>

The button will not be visible if the browser window is beneath 767px

如果浏览器窗口低于767px,则该按钮将不可见

#5


-1  

You need to add !important to the css property. Because your JavaScript code is setting the element style attribute which has more priority than any css selector styles.

您需要在css属性中添加!important。因为您的JavaScript代码设置的元素样式属性优先于任何css选择器样式。

#1


6  

You need to add !important to the CSS property, like:

您需要在CSS属性中添加!important,例如:

 #menu { display:block!important; } 

Your Javascript adds style attribute to the element, which has higher priority than any internal or external CSS styles, unless they "are" !important.

您的Javascript将样式属性添加到元素,该元素具有比任何内部或外部CSS样式更高的优先级,除非它们“是”!重要。

What you can also consider doing to avoid that is to toggle some CSS class in your Javascript instead of setting style attribute. This way you avoid using !important.

您还可以考虑做的是避免这种情况,在Javascript中切换一些CSS类而不是设置样式属性。这样你就可以避免使用!important。

#2


3  

I suggest to not set an elements style like that, toggle a class on the element is the recommended way

我建议不要设置这样的元素样式,在元素上切换类是推荐的方法

Side note, I also changed from id to class, which is also recommended

旁注,我也从id改为class,这也是推荐的

Also, specificity is the reason, pointed out already in comments/answers, why your code doesn't work, more to read here: https://developer.mozilla.org/en/docs/Web/CSS/Specificity

此外,特殊性是原因,在评论/答案中已经指出,为什么你的代码不起作用,更多内容在这里阅读:https://developer.mozilla.org/en/docs/Web/CSS/Specificity

var b = document.querySelector(".menu-button");
b.addEventListener("click", function(e) {
  document.querySelector(".menu").classList.toggle("show");
});
.menu {
  display: none;
}
.menu.show {
  display: block;
}


@media screen and (min-width:640px) {
    .menu {
        display: block;
    }
}
<div class="menu show">Hi, I'm a menu element</div>
<button class="menu-button">Show/Hide</button>

#3


1  

Connexo has pointed out the answer but an expansion may be of some use to you and others who come here in the future.

Connexo已经指出了答案,但扩展可能会对您和将来来到这里的其他人有所帮助。

The 'style' of an HTML element can be set in at least 3 places. The browser will have to decide which should win should there be a *. The rules used are called 'specificity'. There is a good article on this topic here https://css-tricks.com/specifics-on-css-specificity/ if you want a fuller explanation.

HTML元素的“样式”可以设置在至少3个位置。如果发生冲突,浏览器必须决定哪个应该赢。使用的规则称为“特异性”。如果您想要更全面的解释,请在https://css-tricks.com/specifics-on-css-specificity/上找到关于此主题的好文章。

Roughly, any styling defined in the initial HTML 'style' attribute is most powerful so this will win in over a CSS file rule. Importantly, setting the style as you have done in your use case, operates on the HTML style attribute.

粗略地说,在初始HTML“样式”属性中定义的任何样式都是最强大的,因此这将胜过CSS文件规则。重要的是,在用例中设置样式,操作HTML样式属性。

Therefore, your CSS is being overruled by the style attribute setting in your code.

因此,您的CSS被代码中的样式属性设置所取代。

For a pure JS solution you could look at adding a listener to the window onResize event. If you do research that approach please be aware that in some browsers the event fires for every pixel of the size change, so look for a solution that takes that into consideration like this one otherwise the function will be triggered multiple times and may reduce the joy you bring to your users.

对于纯JS解决方案,您可以考虑向窗口onResize事件添加一个监听器。如果您研究这种方法请注意,在某些浏览器中,事件会触发尺寸变化的每个像素,因此请寻找一个考虑到这一点的解决方案,否则该功能将被多次触发并可能降低喜悦你带给你的用户。

#4


0  

As other comments suggested, you are trying different things in your code. I recommend a css solution, you can look into what most grids use to style their media queries to show / hide elements when browserwindow is being resized or the monitorsize becomes smaller.

正如其他评论建议的那样,您在代码中尝试了不同的东西。我建议使用css解决方案,您可以查看大多数网格用于设置其媒体查询的样式,以便在调整浏览器窗口大小或监视器缩小时显示/隐藏元素。

A very cool, light-weight grid is called simplegrid.

一个非常酷,轻量级的网格称为简单网格。

https://github.com/ThisIsDallas/Simple-Grid/blob/master/simplegrid.css

at line 177 the media query for 'handheld' devices start. So for instance adding this to your HTML document:

在第177行,“手持式”设备的媒体查询开始。因此,例如将其添加到HTML文档中:

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://github.com/ThisIsDallas/Simple-Grid/blob/master/simplegrid.css">
</head>
<body>
<button class="hide-on-mobile">MyButton</button>
</body>

The button will not be visible if the browser window is beneath 767px

如果浏览器窗口低于767px,则该按钮将不可见

#5


-1  

You need to add !important to the css property. Because your JavaScript code is setting the element style attribute which has more priority than any css selector styles.

您需要在css属性中添加!important。因为您的JavaScript代码设置的元素样式属性优先于任何css选择器样式。