【发布时间】:2018-06-14 18:03:43
【问题描述】:
我有两个随媒体查询一起移动的容器。当他们移动时,我使用 matchMedia 触发一个事件,该事件导致 div 从一个容器移动到另一个容器。
刷新页面时出现问题。 css 媒体查询有效,但 matchMedia 仅在查询更改时有效。如果你以低于 1000px 的宽度重新加载 codepen,你会发现问题。
我已经搜索并阅读了一些答案,但我是 JS 新手,并且对我应该和不应该调用的内容持谨慎态度(尤其是在监听大小变化时)。
我应该只使用 enquire.js 吗?我读过它没有这个问题。或者有什么简单的解决方法?
<header>
<div class="container" id="container1">
<div class="item">1</div>
<div class="item" id="moveMe">2</div>
<div class="item" id="item3">3</div>
</div>
<div class="container" id="container2">
<div class="item" id="item4">4</div>
</div>
</header>
css
header{
display: flex;
justify-content: space-around;
align-items: center;
width: 100%;
padding: 1rem;
background: #eaeaea;
}
@media (max-width: 1000px){
header{
flex-direction: column;
}
}
.container{
display: flex;
padding: 2rem;
}
#container1{
background: red;
}
#container2{
background: blue;
}
.item{
padding: 2rem;
margin: 2rem;
background: white;
}
js
var container1 = document.getElementById('container1');
var container2 = document.getElementById('container2');
var moveMe = document.getElementById('moveMe');
var item3 = document.getElementById('item3');
var item4 = document.getElementById('item4');
matchMedia("(max-width: 1000px)").addListener(function(mql){
if(mql.matches){
container2.insertBefore(moveMe, item4);
} else {
container1.insertBefore(moveMe, item3);
}
})
*edit: RE i.terrible 的建议我尝试拆分代码以便在 window.onload 上运行它。
var mql = window.matchMedia("(max-width: 1000px)").addListener(checkMedia);
window.onload = checkMedia(mql);
function checkMedia(mql){
if(mql.matches){
container2.insertBefore(moveMe, item4);
} else {
container1.insertBefore(moveMe, item3);
}
}
虽然没用...
*edit2:啊……这行得通。我在上面搞砸了。
var mql = window.matchMedia("(max-width: 1000px)");
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
container2.insertBefore(moveMe, item4);
} else {
container1.insertBefore(moveMe, item3);
}
}
【问题讨论】:
标签: javascript html css media-queries