如何使用 javascript 或 jquery 以像素精度程序化地调整媒体查询?



>我有多个以 20px 为增量的媒体查询,可将顶部边距调整 5-10px 以创建流畅的高度调整大小效果。

有没有办法使用 javascript 或 jquery 以 1-2px 的增量做到这一点?下面是我目前正在使用的代码,但我很好奇这是否可以以更简洁的方式仅用几行代码来完成,以创建更流畅的效果。

div ID 是#underslider1

@media (min-width:1000px) and (max-width:1020px) {
#underslider1 { margin-top: 90px !important;}
}
@media (min-width:980px) and (max-width:1000px) {
#underslider1 { margin-top: 85px !important;}
}
@media (min-width:960px) and (max-width:980px) {
#underslider1 { margin-top: 80px !important;}
}
@media (min-width:940px) and (max-width:960px) {
#underslider1 { margin-top: 75px !important;}
}
@media (min-width:920px) and (max-width:940px) {
#underslider1 { margin-top: 70px !important;}
}
@media (min-width:900px) and (max-width:920px) {
#underslider1 { margin-top: 65px !important;}
}
@media (min-width:880px) and (max-width:900px) {
#underslider1 { margin-top: 55px !important;}
}
@media (min-width:860px) and (max-width:880px) {
#underslider1 { margin-top: 45px !important;}
}
@media (min-width:840px) and (max-width:860px) {
#underslider1 { margin-top: 35px !important;}
}
@media (min-width:820px) and (max-width:840px) {
#underslider1 { margin-top: 25px !important;}
}
@media (min-width:790px) and (max-width:820px) {
#underslider1 { margin-top: 10px !important;}
}

这不会给出完全相同的结果,但它可能会有所帮助:

@media (min-width: 790px) and (max-width: 1020px) {
#underslider1 {
margin-top: calc( 10px + (90 - 10) * ( (100vw - 790px) / ( 1020 - 790) ));
}
}

您可以使用JavaScript APIwindow.matchMedia并在循环中以编程方式编写所有这些内容...

最新更新