javascript 动态计算一个div宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5833869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:30:58  来源:igfitidea点击:

Dynamically calculate a div width

javascript

提问by Mori

Here are sample divisions:

以下是示例分区:

#grandparent {
  width: 100px;
}
#parent {
  overflow: auto;
  height: 100px;
}
.child {
  overflow: hidden;
  margin-left: 10px;
}
<div id="grandparent">

  <div id="parent">

    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>
    <div class="child">1000000000000000000000000</div>

  </div>

</div>

The <div class="child">width value is always 10 pixels less than <div id="parent">width value. How can it be calculated so any width value is given to <div id="parent">, its child gets 10 pixels less than that?

<div class="child">宽度值总是小于10个像素<div id="parent">宽度的值。如何计算,以便将任何宽度值赋予<div id="parent">,其子项得到的值比该值少 10 个像素?

Any help is very much appreciated!

很感谢任何形式的帮助!

Mike

麦克风

回答by Tanner Ottinger

With jQuery, this is very easy. Just subtract 10 from what.innerWidth()Here:

使用 jQuery,这很容易。只需从what.innerWidth()这里减去 10 :

$(".child").css('width', $('#parent').innerWidth()-10);

You could also do it like this:

你也可以这样做:

$(".child").each(function(){
    $(this).css('width', $(this).parent().innerWidth()-10);
});

-Which means you could have more than one parent, without having to know the id.

- 这意味着您可以拥有多个父级,而无需知道id.

Normal JS

普通JS

You can use the clientWidthproperty of an HTML element object. Like this:

您可以使用clientWidthHTML 元素对象的属性。像这样:

var targetParent = document.getElementById('parent'); // or whatever
var targets = targetParent.getElementsByClassName('child');
for(var i=0;i<targets.length;i++) targets[i].parentNode.style.width = targets[i].clientWidth - 10;

Hope this helps! - Tanner.

希望这可以帮助!- 坦纳。

回答by Chandu

Try this css for parent:

为父母试试这个 css:

#parent {
 overflow:auto; height:100px;
 padding: 0 5px 0 5px;
}

回答by Chris Eberle

That's what the selectors are for in CSS:

这就是 CSS 中选择器的用途:

#parent.div {
    width: 100%;
    margin-left: 10px;
    margin-right: 10px;
}