在小屏幕上插入之前 div,在大屏幕上插入之后



在我的示例中,我尝试仅在大屏幕上将小div 插入大div 上方。然后在调整窗口大小时,我想仅在小屏幕上插入相同的小 Div 和 Medium Div。 问题是每次我调整窗口大小时,小 Div 都会一遍又一遍地添加,我希望它只添加一次。

请注意,我正在寻找JS或jQuery解决方案。

问候。

var smallDiv = '<div class="small">Small Div</div>';
function moveDiv() {
if ($(window).width() < 800) {
$(smallDiv).insertBefore(".large");
} else {
$(smallDiv).insertAfter(".medium");
}
}
moveDiv();
$(window).resize(moveDiv);
<!-- begin snippet: js hide: false console: true babel: false -->
.large {
width: 100%;
height: 80px;
background-color: darkgray;
}
.medium {
width: 100%;
height: 50px;
background-color: goldenrod;
}
.small {
width: 100%;
height: 30px;
background-color: aquamarine;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="large">Large Div</div>
<div class="medium">Medium Div</div>

Renlado的答案缺少部分问题。您可以按照建议使用弹性框,并使用 order 属性对元素进行排序。

.container {
display: flex;
flex-direction: column;
}
.container>div {
order: 1
}
.container>.small {
order: 0;
}
@media only screen and (max-width: 800px) {
.container .small {
order: 2;
}
}
<div class="container">
<div class="large">Large Div</div>
<div class="medium">Medium Div</div>
<div class="small">Small Div</div>
</div>

不是jQuery的粉丝,所以让我们用CSS来做

.container {
display: flex;
flex-direction: column;
}
@media only screen and (max-width: 800px) {
.container {
flex-direction: column-reverse;
}
}
<div class="container">
<div class="large">Large Div</div>
<div class="medium">Medium Div</div>
</div>

最新更新