Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.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 如何设置容器宽度计算其子容器的宽度_Javascript_Jquery_Html - Fatal编程技术网

Javascript 如何设置容器宽度计算其子容器的宽度

Javascript 如何设置容器宽度计算其子容器的宽度,javascript,jquery,html,Javascript,Jquery,Html,我有一个容器,里面有n个div。我需要根据它调整容器的大小。我知道这可以使用jquery库完成,如下所示 JQuery $(document).ready(function(){ setContainerWidth(); }); $(window).resize(function(){ setContainerWidth(); }); function setContainerWidth() { $('.container').css('width', 'auto');

我有一个容器,里面有n个div。我需要根据它调整容器的大小。我知道这可以使用jquery库完成,如下所示

JQuery

$(document).ready(function(){
    setContainerWidth();
});

$(window).resize(function(){
   setContainerWidth();
});

function setContainerWidth()
{
    $('.container').css('width', 'auto'); //reset
    var windowWidth = $(document).width();
    var blockWidth = $('.block').outerWidth(true);
    var maxBoxPerRow = Math.floor(windowWidth / blockWidth);
    $('.container').width(maxBoxPerRow * blockWidth);
}
这次我需要用纯javascript来解决一些插件问题。我把代码分解成下面的代码,中间有任何帮助,谢谢。 Javascript

function setContainerWidth(){
    var container_width = document.getElementById('container').offsetWidth;
    var width = document.body.clientWidth
    var block_width = document.getElementsByClassName("block").offsetWidth;

    container.style.width = "auto"
    var maxBoxPerRow = Math.floor(width / block_width)
    container.offsetWidth(maxBoxPerRow * block_width)
}


纯javascript翻译中缺少一些东西:

function setContainerWidth()
{
    var container = document.getElementById('container');
    container.style.width = "auto";
    var window_width = window.innerWidth;
    var block_width = document.getElementsByClassName("block")[0].offsetWidth;
    var maxBoxPerRow = Math.floor(window_width / block_width);
    container.style.width = (maxBoxPerRow * block_width) + 'px';
}

document.getElementsByClassName()
返回元素数组。您需要使用
document.getElementsByCassName('block')[0]
我以前尝试过,但在ma案例中不起作用,甚至尝试了
id
而不是
class
for box仍然没有成功如何在使用纯JS调整窗口大小时使用此选项像这样
window.onresize=function(event){…}