javascript - 如何使用 onWindowResize 将容器居中调整大小

标签 javascript jquery css

我正在使用一个脚本,该脚本在调整窗口大小时调整我的 .container 的大小。这是我的页面:http://cjehost.com/qt/nipt/page6.php

如果您调整浏览器窗口的大小,您将看到容器调整大小但不会保持居中。有没有办法让我的容器居中?这是我的脚本:

	 // Resize the map to fit within the boundaries provided

	function resize(maxWidth, maxHeight) {
	  var image = $('img'),
	    imgWidth = image.width(),
	    imgHeight = image.height(),
	    newWidth = 0,
	    newHeight = 0;

	  if (imgWidth / maxWidth > imgHeight / maxHeight) {
	    newWidth = maxWidth;
	  } else {
	    newHeight = maxHeight;
	  }
	  image.mapster('resize', newWidth, newHeight, resizeTime);
	}

	 // Track window resizing events, but only actually call the map resize when the
	 // window isn't being resized any more

	function onWindowResize() {

	  var curWidth = $(window).width(),
	    curHeight = $(window).height(),
	    checking = false;
	  if (checking) {
	    return;
	  }
	  checking = true;
	  window.setTimeout(function() {
	    var newWidth = $(window).width(),
	      newHeight = $(window).height();
	    if (newWidth === curWidth &&
	      newHeight === curHeight) {
	      resize(newWidth, newHeight);
	    }
	    checking = false;
	  }, resizeDelay);
	}

	$(window).bind('resize', onWindowResize);

我的CSS:

 .container {margin:0 auto;}

最佳答案

对于这个,我真的会推荐一种 CSS 方法而不是 JavaScript 方法。带有 @media 查询的响应式 CSS 就是为此而生的。不要将 DOM 操作与 JavaScript 一起使用,这在性能方面确实代价高昂。

CSS 居中

.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

@media 查询

@media screen and (max-width: 380px) {
  // Styles for Mobiles
}
@media screen and (min-width: 381px) and (max-width: 760px) {
  // Styles for Tablets
}
@media screen and (min-width: 761px) {
  // Styles for Desktops
}

您可以在线找到详尽的列表。

关于javascript - 如何使用 onWindowResize 将容器居中调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41515316/

相关文章:

javascript - Durandal:找不到 view/viewModel 时处理 RequireJS 错误

javascript - 在 Google Apps 脚本中解析 JSON 时出现未定义错误

javascript - 在输入类型图像中更改 svg 中的填充颜色

javascript - 如何从每个返回的div中获取div id?

javascript - 通过 AppleScript 使用 Javascript 获取图像尺寸

javascript - 如何检测窗外的 MouseUp 事件?

CSS 粘性页眉/页脚和完全拉伸(stretch)的中间区域?

javascript - Spotify 应用程序 - 维护页面之间的状态

css - 垂直对齐列表内的 <a> 标签

javascript - Selenium (C#),使用 JavaScript 查找元素失败