我使用 resize() 方法来运行一个函数,该函数将返回 不同的视口(viewport)大小,如 992,768 等。问题是 每次执行函数都会导致 DOM 出现故障。例子 在codepen https://codepen.io/paul-solomon/pen/WBEgQe
//javascript
$(window).resize(function(){
nh_masonry.data.loadorder();
});
//css
.masonry_grid_quarter__container{
margin-bottom: 8px;
column-count:3;
column-gap:8px;
}
@media screen and (max-width:992px){
.masonry_grid_quarter__container{
column-count:2;
}
}
@media screen and (max-width:768px){
.masonry_grid_quarter__container{
column-count:2;
}
}
@media screen and (max-width:580px){
.masonry_grid_quarter__container{
column-count:1;
}
}
预期结果:调整大小函数在特定视口(viewport)执行 实际结果:多次执行调整大小,造成 DOM 故障。
最佳答案
您需要一个变量来跟踪 DOM 的当前状态。
让我们创建一个名为 currentViewPort
的变量,其值为“桌面”、“平板电脑”或“移动设备”。
当窗口大小调整时,我们将切换currentViewPort
的值。如果 currentViewPort 已经与我们的屏幕布局匹配,那么我们将不会再次调用该函数。仅当我们输入不同的布局时才会调用它。
这是在行动:https://codepen.io/anon/pen/GaGboG?editors=1111
var App = (function ($) {
var nh_masonry = {};
var currentViewPort = ""
//sets initial reorder variable
nh_masonry.vars = { reorder : false}
nh_masonry.onload = function () {
// when the document is loaded sets the reorder variable to true
// and also loads the order object method
nh_masonry.vars.reorder = !nh_masonry.vars.reorder;
nh_masonry.data.loadorder();
$(window).resize(function(){
// re-set layout after resize
if($( window ).width() <= 992 && $( window ).width() > 768 && currentViewPort !== "desktop"){
currentViewPort = "desktop"
console.log("desktop");
nh_masonry.data.loadorder();
// nh_masonry.responsive.tablet();
// nh_masonry.responsive.mobile();
} else if ($( window ).width() == 768 && currentViewPort !== "tablet"){
currentViewPort = "tablet"
console.log("tablet");
nh_masonry.data.loadorder();
// nh_masonry.responsive.tablet();
// nh_masonry.responsive.mobile();
} else if ($( window ).width() < 768 && $( window ).width() >= 380 && currentViewPort !== "mobile"){
currentViewPort = "mobile"
console.log("mobile");
nh_masonry.data.loadorder();
// nh_masonry.responsive.tablet();
// nh_masonry.responsive.mobile();
}
})
};
关于javascript - 调整大小函数多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331943/