gpt4 book ai didi

javascript - 如何根据浏览器大小更改元素的顺序?

转载 作者:太空宇宙 更新时间:2023-11-04 02:28:07 24 4
gpt4 key购买 nike

我有三个水平堆叠的按钮。单击每个按钮时,会显示一个 div 元素。当浏览器调整为移动 View 时,我希望元素垂直堆叠。默认情况下会发生这种情况,但我想将 div 元素直接堆叠在与其关联的按钮下方。

这就是我要显示的内容(桌面左侧,移动右侧):

Correct desktop view enter image description here

这是我得到的(桌面左侧,移动右侧):

Correct desktop view Incorrect mobile view

这是基本的 HTML。如果我将关联的 div 直接移动到按钮下方,它在移动设备上看起来不错,但在桌面设备上看起来不正确。

<button onclick="updateValue(1)">Button 1</button>
<button onclick="updateValue(2)">Button 2</button>
<button onclick="updateValue(3)">Button 3</button>
<div id="div-1"><span>This is div 1!</span></div>
<div id="div-2"><span>This is div 2!</span></div>
<div id="div-3"><span>This is div 3!</span></div>

我确实尝试在按钮上使用 float ,但无法获得所需的输出。这是一个 fiddle ,展示了我现在拥有的东西。

JSFIDDLE

那么如何在桌面上对元素 button + button + button > div 进行排序,在移动设备上对 button > div > button > button 进行排序呢?

最佳答案

@Lefka 这里是一个使用 flexbox 模型的例子。
当您将整个页面 View 中的示例调整为小于 420 像素的窗口时,元素将按您预期的方式重新排序。
希望它能帮助您了解您的需求。

function updateValue(newValue) {
for (i = 1; i <= 3; i++) {
var element = document.getElementById("div-" + i);
element.className = "";
if (newValue === i) {
element.className = "show";
}
}
}
div {
display: none;
}

.show {
display: block;
}

.flex-parent {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-content: stretch;
align-items: flex-start;
}

button {
flex: 0 0 auto;
}

[id^="div-"] {
flex: 1 1 100%;
}

@media screen and (max-width: 420px) {
.flex-parent {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-content: stretch;
align-items: flex-start;
}

.button-1 {
order: 0;
}

.button-2 {
order: 2;
}

.button-3 {
order: 4;
}

#div-1 {
order: 1;
}

#div-2 {
order: 3;
}

#div-3 {
order: 5;
}
}
<div class="flex-parent">
<button class="button-1" onclick="updateValue(1)">Button 1</button>
<button class="button-2" onclick="updateValue(2)">Button 2</button>
<button class="button-3" onclick="updateValue(3)">Button 3</button>
<div id="div-1"><span>This is div 1!</span></div>
<div id="div-2"><span>This is div 2!</span></div>
<div id="div-3"><span>This is div 3!</span></div>
</div>

关于javascript - 如何根据浏览器大小更改元素的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012008/

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