我已经尝试了if else
语句,它应该相当简单,但我似乎无法在调整大小超过650px之后反转回合。
基本上,当窗口低于650宽度时,我试图将盒子包裹在div中,然后在调整大小超过650px后展开。
我该怎么做?
$(window).resize(function() {
if ($(window).width() < 650)
$('.box').wrap("<div class='boxwrap'><div/>")
});
$(window).resize(function() {
if ($(window).width() > 650)
$('.box').unwrap("<div class='boxwrap'><div/>")
});
&#13;
#cat-area {
width: 100%;
display: inline-block;
text-align: center;
background-color: red;
}
#cat-container {
background-color: yellow;
width: 92.5%;
margin: 0 auto;
display: flex;
justify-content: space-between;
}
.box {
display: inline-block;
width: 20%;
height: 20%;
max-height: 300px;
max-width: 300px;
min-height: 100px;
min-width: 100px;
padding: 1%;
background-color: #d7d7d7;
}
@media only screen and (max-width: 650px) {
#cat-area {
width: 100%;
display: block;
text-align: center;
background-color: red;
}
#cat-container {
background-color: blue;
width: 92.5%;
display: block;
}
.box {
position: relative;
display: block;
margin: 4px 0px;
}
.boxwrap {
background-color: #d7d7d7;
width: 100%;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cat-area">
<div id="cat-container">
<img class="box" src="http://via.placeholder.com/200x200">
<img class="box" src="http://via.placeholder.com/200x200">
<img class="box" src="http://via.placeholder.com/200x200">
<img class="box" src="http://via.placeholder.com/200x200">
</div>
</div>
&#13;
答案 0 :(得分:2)
我自己也遇到过类似的问题。以下是如何执行此操作的简单演示:
运行以下代码段,将其展开到全屏,然后调整浏览器大小以使其正常工作。
$(function() {
var resizeTimer;
var initialSize = $(window).width();
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
var delayedSize = $(window).width();
// if we resize the page but we don't cross the 650 threshold, do nothing
if ((initialSize > 650 && delayedSize > 650) || (initialSize < 650 && delayedSize < 650)) {
return
}
// else if we resize the page and cross the 650 threshold, do something
else {
if (delayedSize > 650) {
$('#cat-container').unwrap('#cat-area');
} else if (delayedSize <= 650) {
$('#cat-container').wrap('<div id="cat-area"></div>');
}
}
initialSize = delayedSize;
}, 250);
});
});
#cat-area {
background-color: gold;
padding: 10px;
}
#cat-container {
background-color: slategray;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cat-area">
<div id="cat-container">
<img class="box" src="http://via.placeholder.com/200x200">
<img class="box" src="http://via.placeholder.com/200x200">
<img class="box" src="http://via.placeholder.com/200x200">
<img class="box" src="http://via.placeholder.com/200x200">
</div>
</div>