javascript - $(window).resize 在高度/宽度条件下无法正确触发功能

标签 javascript jquery css

我有一个固定位置的全屏图片库。容器 div 高度是通过 jQuery 设置的,下一个 div (#page) 的 margin-top 等于 window.height。

这是这段代码:

var windowH = $(window).height();
var windowW = $(window).width();

function marginTop() {
    var currentH = $(window).height();
    $("#page").css("margin-top", currentH +'px');
    $("#image-gallery").css("height", currentH +'px');
    console.log('mTop fired!');
};

$(window).resize(function() {
        var newH = $(window).height();     // Records new windows height after resize
        var newW = $(window).width();
        var maxH = windowH + 90;        // Sets a positive delta of some px
        var maxW = windowW + 60;
        var minH = windowH - 90;      // Sets a negative delta of some px
        var minW = windowW - 60;
            if(newH > maxH) {           // If the height difference is more than 50px, then set new marginTop for #page
                marginTop();
                console.log('fire for bigger height');
            } else if(newH < minH) {
                marginTop();
                console.log('fire for smaller height');
            } else if(newW > maxW) {
                marginTop();
                console.log('fire for bigger width');
            } else if(newW < minW ) {
                marginTop();
                console.log('fire for smaller width');
            }
});

我将条件拆分为多个 else if 语句,因为它不能正常工作,我必须检查它何时工作,何时不工作。

各种 if...elseif...elseif... 解决了移动浏览器上的一个问题:如果没有该增量,#image-gallery div 会在地址栏出现或消失时改变尺寸,从而导致断断续续的调整div 的高度。此外,我也不想因为桌面视口(viewport)的微小变化而重绘整个东西。

但是它有一些问题,因为它不能正常工作。特别是:

  • marginTop() 仅在高度较小的 window.resize 时触发(从 console.log 中检查)
  • 在桌面上,如果通过右上角的按钮调整窗口大小,它根本不会触发。
  • 删除所有 if-else-if 条件,它在任何情况下在桌面上都能正常工作(但地址栏在移动设备上仍然是个问题)

无法弄清楚,代码对我来说似乎没问题,但对浏览器来说却不行。问题在哪里?

在最新的 Firefox 和 Chrome 上测试

最佳答案

这里有很多小问题。您的 if 语句将永远不会达到宽度比较。首先,宽度与高度在 if else 中,然后始终首先评估高度,如果调整高度,则永远不会达到宽度。

接下来,您在 var windowH = $(window).height(); 中看到的“当前高度|宽度”永远不会重置。这意味着,如果用户以 200:150 的视口(viewport)(比如浏览器最小化)出现,则高度:宽度将始终基于 200:150 进行测量。这将带来与使用更大视口(viewport)的人截然不同的体验。

另一个经常在调整窗口大小时发现的问题是您的代码会触发多次。这可能会导致重叠命令的重大问题,从而导致双重反馈。

下面是我将如何处理这个问题和建议的重建。

/*	simple method to get the current window size as an object where h=height && w=width	*/
function getWindowSize() {
	return { h: $(window).height(), w: $(window).width() };
}

function doWork(typ, msg) {
	//	report msg of change to console
	console.log(typ == 'h' ? 'HEIGHT:\t' : 'WIDTH:\t', msg);
	
	//	we really only need fire your method if height has changed
	if (typ == 'h') marginTop();
	
	//	a change was made, now to reset 
	window.sizeCheck = getWindowSize();
}

//	your original method
//	brokered off so it can be used independently 
function marginTop() {
	var currentH = $(window).height();
	console.log('currentH', currentH)
	$("#page").css("margin-top", currentH +'px');
	$("#image-gallery, #page").height(currentH);
	console.log('mTop fired!');
}

/*	action area for window resize event	*/
function windowResize() {
	//	made my variables short and sweet,
	//	sch=sizeCheck, scu=sizeCurrent
	var sch = window.sizeCheck,	//	get previously set size
		scu = getWindowSize(),
		maxH = sch.h + 90,
		minH = sch.h - 90,
		maxW = sch.w + 60,
		minW = sch.w - 60;
	
	if (scu.h > maxH) doWork('h', 'View Got <b>Taller</b>');
	else if (scu.h < minH) doWork('h', 'View Got <i>shorteR</i>');
	
	//	for what you want, the following isn't even really nec
	//	but i'll leave it in so you can see the work
	if (scu.w > maxW) doWork('w', 'View Got <b>Wider</b>');
	else if (scu.w < minW) doWork('w', 'View Got <i>thinneR</i>');
}

$(function() {
	//	ezier to maintain one global variable than to scope 
	//	shot 2 which could easily be overriden in a latter method, 
	//	by simple confusion
	window.sizeCheck = getWindowSize();
	
	//	call of event to establish correct margin for the page div
	marginTop()
	
	$(window).resize(function(e) {
		//	this will clear our timer everytime resize is called
		if (this.tmrResize) clearTimeout(this.tmrResize);
		//	resize is called multiple times per second, 
		//	this helps to seperate the call,
		//	and ensure a little time gap (1/4 second here)
		this.tmrResize = setTimeout(windowResize, 250);
	});
})
html, body { margin: 0; padding: 0; }
#image-gallery {
	background: blue;
	color: white;
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
}
#page { background: white; color: red; height: 400px; position: relative; z-index: 1; }
p { padding: 3em; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-gallery">
	<p>
		image Gallery
	</p>
</div>
<div id="page">
	<p>
		next page
	</p>
</div>

关于javascript - $(window).resize 在高度/宽度条件下无法正确触发功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35989292/

相关文章:

javascript - 什么是 JS 正则表达式来匹配文本中的 sha256 单词哈希?

javascript - 如何将选定价格和输入复选框价格Jquery结合起来?

javascript - 如何修复基于 JSON 响应的 React 组件填充?

javascript - 如何从组件容器中设置 React 组件的样式?

jquery - 选择一天时应用不同的样式 - jQuery multidatepicker

javascript - 控制动画

javascript - 同位素转换 'flash' 错误(Chrome)

javascript:将参数传递/接受给 func

javascript - 动态 html 表单数据 AJAX 重定向到 google 表格错误

javascript - 如何使固定元素消失在非固定元素后面