我正在使用一个脚本,该脚本在调整窗口大小时调整我的 .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/