我正在尝试计算浏览器调整大小的百分比,但我似乎无法在调整大小开始之前捕获窗口的大小,然后在完成后调整大小。
$(function () {
var originalHeight = $(window).height();
$(window).resize(function (e) {
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
$('body').html('old: ' + originalHeight + ' | new: ' + newHeight);
originalHeight = newHeight;
});
});
两个数字(originalHeight和newHeight)总是因某种原因匹配。有什么我可以模拟另外两个事件,例如beginResize
或endResize
吗?如果我能做到那么我可以这样做:
$(function () {
var originalHeight;
$(window).beginResize(function () {
originalHeight = $(window).height();
});
$(window).endResize(function () {
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
alert(percentageChange);
});
有什么想法吗?
我能够在空白环境中本地复制,但不能在jsfiddle上复制。我只能得出结论,jsfiddle上的iframe环境正在干扰。
当我执行以下页面时:
<!DOCTYPE html>
<html>
<head>
<title>Isolate</title>
<script type="text/javascript" src="~/Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function () {
var originalHeight = $(window).height();
$(window).resize(function (e) {
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
$('body').append('old: ' + originalHeight + ' | new: ' + newHeight + ' | percentage: ' + percentageChange + '<br />');
originalHeight = newHeight;
});
});
</script>
</head>
<body>
</body>
</html>
我得到以下结果:
old: 417 | new: 418 | percentage: 1.0023980815347722
old: 418 | new: 418 | percentage: 1
old: 418 | new: 419 | percentage: 1.0023923444976077
old: 419 | new: 419 | percentage: 1
old: 419 | new: 420 | percentage: 1.0023866348448687
old: 420 | new: 420 | percentage: 1
old: 420 | new: 422 | percentage: 1.0047619047619047
old: 422 | new: 422 | percentage: 1
old: 422 | new: 423 | percentage: 1.0023696682464456
old: 423 | new: 423 | percentage: 1
似乎resize事件每次调整大小都会运行两次。第一次检测到原始值和新值之间的差异,但第二次值是相同的,因为第一次运行会将originalHeight更新为newHeight。
您可以在this fiddle中看到未发生此双重事件运行问题。每个条目都显示旧的和新的不同值。
答案 0 :(得分:3)
此行为完全取决于浏览器。它既不在Opera,Firefox也不在IE中,而是在Chrome中。
为了避免这种行为,您只需检查上一次更新是否发生在某个时间间隔内(例如最后100ms)(fiddle,在所有常见浏览器中测试过):
$(function () {
var originalHeight = $(window).height();
var originalHeightTime = new Date();
$(window).resize(function (e) {
var newTime = new Date();
if (newTime - originalHeightTime < 100)
return;
var newHeight = $(window).height();
var percentageChange = newHeight / originalHeight;
$('body').html('old: ' + originalHeight + ' | new: ' + newHeight + ' | percentage: ' + percentageChange);
originalHeight = newHeight;
originalHeightTime = newTime;
});
});