如何使用onWindowResize在容器上调整大小

时间:2017-01-06 22:22:50

标签: 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;}

2 个答案:

答案 0 :(得分:0)

对于这个,我建议使用CSS方法而不是JavaScript方法。具有@media查询的响应式CSS就是为此而存在的。不要将DOM操作与JavaScripts一起使用,这在性能方面确实很昂贵。

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
}

您可以在线找到详尽的清单。

答案 1 :(得分:0)

我设法通过用.container(我的容器div)替换窗口来完成这项工作。它仍然有点笨拙 - 即当我从较小的分辨率切换到全屏时,容器并不总是调整大小。这是我的工作代码:



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

function onWindowResize() {

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



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


});




这是一个工作小提琴:enter link description here

我找到了这种方法的参考,并在这里弄曲:enter link description here

感谢@LBF