Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用onWindowResize在调整大小时将容器居中_Javascript_Jquery_Css - Fatal编程技术网

Javascript 如何使用onWindowResize在调整大小时将容器居中

Javascript 如何使用onWindowResize在调整大小时将容器居中,javascript,jquery,css,Javascript,Jquery,Css,我正在使用一个脚本,该脚本在调整窗口大小时调整.container的大小。这是我的页面: 如果调整浏览器窗口的大小,将看到容器调整大小,但不会保持居中。有没有办法让我的容器居中?这是我的剧本: //调整地图大小,使其符合提供的边界 函数调整大小(maxWidth、maxHeight){ var image=$('img'), imgWidth=image.width(), imgHeight=image.height(), newWidth=0, newHeight=0; 如果(imgWidt

我正在使用一个脚本,该脚本在调整窗口大小时调整.container的大小。这是我的页面:

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

//调整地图大小,使其符合提供的边界
函数调整大小(maxWidth、maxHeight){
var image=$('img'),
imgWidth=image.width(),
imgHeight=image.height(),
newWidth=0,
newHeight=0;
如果(imgWidth/maxWidth>imgHeight/maxHeight){
newWidth=maxWidth;
}否则{
newHeight=maxHeight;
}
mapster('resize',newWidth,newHeight,resizeTime);
}
//跟踪窗口大小调整事件,但仅在
//窗口不再调整大小
函数onWindowResize(){
var curWidth=$(窗口).width(),
curHeight=$(窗口).height(),
检查=假;
如果(检查){
返回;
}
检查=真;
setTimeout(函数(){
var newWidth=$(窗口).width(),
newHeight=$(window.height();
如果(newWidth==curWidth&&
newHeight==curHeight){
调整大小(新宽度、新高度);
}
检查=假;
},重定尺寸延迟);
}

$(窗口).bind('resize',onWindowResize)对于这个方法,我建议使用CSS方法而不是JavaScript方法。带有
@media
查询的响应式CSS就是针对这一点的。不要对Java脚本使用DOM操作,这在性能方面是非常昂贵的

CSS居中

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

@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
}

您可以在网上找到一个详尽的列表。

我通过用.container(我的container div)替换窗口来实现这一点。它仍然有点笨重-也就是说,当我从较小的分辨率切换到全屏时,容器并不总是调整大小。这是我的工作代码:

//跟踪窗口大小调整事件,但仅在
//窗口不再调整大小
函数onWindowResize(){
var curWidth=$('.container').width(),
curHeight=$('.container').height(),
检查=假;
如果(检查){
返回;
}
检查=真;
setTimeout(函数(){
var newWidth=$('.container').width(),
newHeight=$('.container').height();
如果(newWidth==curWidth&&
newHeight==curHeight){
调整大小(新宽度、新高度);
}
检查=假;
},重定尺寸延迟);
}
$(窗口).bind('resize',onWindowResize);
$(窗口).resize(onWindowResize);

});
$(窗口)。调整大小(onWindowResize)刚刚看到并添加了它-谢谢。我的容器在这个页面上是有响应的,但并没有保持在中心位置,特别是当您进入较小的断点时。左边有一个15px的垫子,右边靠着窗户。有什么想法吗?我已经在运行bootstrap,它通常会调整图像的大小,但是由于bootstrap和我正在运行的另一个jquery脚本(imagemapster)之间存在冲突,我正在使用上面的脚本(函数resize(maxWidth,maxHeight)…)使图像响应。如果加载页面时不使用imagemapster代码,则图像会有响应。现在容器分区已经居中,我的图像有响应,但它没有在容器分区居中。@phillystyle123啊,我明白了。更正:不仅仅是图像。现在正在调整整个窗口的大小,但不在浏览器窗口中居中。当浏览器窗口变小时,容器向右移动,出现水平滚动。