gpt4 book ai didi

javascript - 根据屏幕大小从菜单中动态删除元素

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:04 25 4
gpt4 key购买 nike

前几天我在一个网站上看到它有几个选项卡 A|B|C|D|E|MORE 现在只要你放大桌面浏览器它就会变成 A|B|C|MORE 然后进一步缩放变化它到 A|MORE,反之亦然缩小。我正在使用 AngularJS 填充我的菜单,所以我想知道如何为此编写指令?

最佳答案

为此,我会使用 CSS 和 Mediaqueries 来做到这一点。实际上这只能在 CSS 中完成。

媒体查询

媒体查询是根据设备/屏幕属性“激活”CSS 选择器及其样式定义的规则。其中:媒体类型、屏幕宽度/高度、设备宽度/高度、分辨率(每英寸像素)、设备像素比、方向……

详细信息:

我的解决方案

  • 我的解决方案使用 flex-box 将主要可见按钮的列扩展到整个可用宽度,因为“更多...”按钮向右浮动并固定宽度。

  • 当减小的宽度“触发”断点时,媒体查询将匹配,隐藏主按钮并显示子菜单中的按钮。

  • 子菜单在 :hover 上打开,不需要 Javascript。

JsFiddle Playground

(应适用于所有现代浏览器,包括 IE 11,仅在 Chrome ~33、FF ~27 中测试)

详情

flex

HTML

<div id="menu">
<ul class="primary">
...
</ul>
<div class="more">
...
</div>
</div>

CSS

#menu {
display: flex;
...
}

#menu .primary {
margin: 0 50px 0 0;
flex: 1;
}

媒体查询

/* hide the buttons that are visibile in the primary menu */
#menu .more li:nth-child(1),
#menu .more li:nth-child(2),
#menu .more li:nth-child(3) {
display: none;
}

/* 1st breakpoint: hide primary button, show the correstponding one in the submenu */
@media screen and (max-width: 350px) {
#menu .primary li:nth-child(3) {
display: none;
}
#menu .more li:nth-child(3) {
display: block;
}
}

/* 2nd breakpoint: ... and so on ... */
@media screen and (max-width: 300px) {
#menu .primary li:nth-child(2) { /* the same procedure ... */ }
#menu .more li:nth-child(2),
#menu .more li:nth-child(3) { /* the same procedure ... */ }
}

完整代码

HTML

<div id="menu">
<ul class="primary">
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
</ul>
<div class="more">
More...
<ul>
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
<li>DDD</li>
<li>EEE</li>
</ul>
</div>
</div>

CSS

/* Make the children elements flex */
#menu {
display: flex;
height: 30px;
}

#menu ul li {
list-style: none;
}

/* The button wraper will flex to full remaining width */
#menu .primary {
margin: 0 50px 0 0;
padding: 0;
display: inline-block;
flex: 1;
}

#menu .primary li {
padding: 5px 10px;
min-width: 50px;
text-align: center;
display: inline-block;
}

/* Place the "more..." button right */
#menu .more {
padding: 5px 10px;
width: 50px;
display: inline-block;
float: right;
}

/* Hide hoverable submenu by default */
#menu .more ul {
display: none;
padding: 0;
margin: 0;
}

/* Show on hover */
#menu .more:hover ul {
display: block;
}


/* Hidden by default, reactivated by the following Mediaqueries */

#menu .more li:nth-child(1),
#menu .more li:nth-child(2),
#menu .more li:nth-child(3) {
display: none;
}

@media screen and (max-width: 350px) {
#menu .primary li:nth-child(3) {
display: none;
}
#menu .more li:nth-child(3) {
display: block;
}
}

@media screen and (max-width: 300px) {
#menu .primary li:nth-child(2) {
display: none;
}
#menu .more li:nth-child(2), #menu .more li:nth-child(3) {
display: block;
}
}

JsFiddle

关于javascript - 根据屏幕大小从菜单中动态删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23585505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com