[英]How to set the container width calculating the width of if its children
I have a container with n number of div inside it. 我有一个容器,里面有n个div。 I need the container to resize according to it children.
我需要根据孩子调整容器的大小。 I know this can be done using jquery library as follows.
我知道这可以使用jquery库完成,如下所示。
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);
}
This time I need to do this with the pure javascript for some plugin issue. 这次,我需要使用纯JavaScript来解决某些插件问题。 I broke down the code till as follows and stuck in the middle any help would be appreciated.
我将代码分解如下,并停留在中间,不胜感激。
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)
}
You are missing a few things from your pure javascript translation: 您从纯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';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.