我有以下行动:
var mtarget = $('.headshots');
var mwin = $(window).width();
var singlephoto = '<div class="officers-group-shot"><img src="my-image.jpg" alt=""></div>';
if (mtarget.length) {
$(window).on("resize", function () {
if (mwin < 800) {
$('.headshots').addClass('d-none');
$(singlephoto).insertBefore('.headshots:first');
} else {
$('.headshots').removeClass('d-none');
}
}).resize();
它按预期工作,只是在拖动屏幕时一遍又一遍地处理insertBefore代码。
如何只插入一次,而在加载或拖动时屏幕小于800px?
谢谢!
答案 0 :(得分:3)
检查您是否已经添加了div,只有在找不到它时才会这样做。
if (mwin < 800) {
var $addedDiv = $(".officers-group-shot");
if ($addedDiv.length == 0) {
$('.headshots').addClass('d-none');
$(singlephoto).insertBefore('.headshots:first');
}
}