如何将 div 的宽度设置为另一个 div 的宽度?

How to set width of div to another div's width?

我正在尝试使用 javascript 将一个 div 的宽度设置为另一个的宽度。在我的例子中,第二个 div 是从第一个克隆而来的。

我 运行 遇到的问题与填充有关,以及 style.width 与 clientWidth/offsetWidth/scrollWidth 的定义方式不同。在下面的示例中,我有两个 div 定义相同,只是宽度不同。按下按钮时,我试图将较小的宽度设置为较大的 - 但结果是它获得较大的宽度加上填充(额外的 20px)。

有没有办法改变线路:

two.style.width = one.clientWidth + 'px';

让两个div的宽度相等?

function setWidth() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  two.style.width = one.clientWidth + 'px';
}
.outer {
  background: red;
  padding: 10px;
  } 
.inner {
  background: green;
  height: 10px;
  } 

#one {
  width: 100px; 
}
#two {
  width:50px;
    }
<div id=one class=outer><div class=inner></div></div>
<br>
<div id=two class=outer><div class=inner></div></div>
<button onclick="setWidth()">SET WIDTH</button>

你应该使用.offsetWidth。它们属于元素,而不是.style。

function setWidth() {
    var w=document.getElementById('one').offsetWidth
    document.getElementById('two').setAttribute("style","width:"+w+"px");
}

宽度未考虑填充。你仍然需要减去它。这样的事情应该有效:

function setWidth() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");

  two.style.width = one.offsetWidth  + 'px';

  //update the width again, subtracting the difference between the first div and the second (which includes padding)
  two.style.width = (two.offsetWidth-((two.offsetWidth - one.offsetWidth)*2))  + 'px';
}

你可以看到它在这里工作:https://jsfiddle.net/igor_9000/55d1pfak/1/

就其价值而言,jQuery 处理起来更容易一些,并获得包括 padding/borders 在内的元素宽度。这可能是您的另一种选择。

希望对您有所帮助!

您可以使用 getComputedStyle:

function setWidth() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  style = window.getComputedStyle(one);
  wdt = style.getPropertyValue('width');
  two.style.width = wdt;
}

这是一个fiddle

您需要考虑 one 的填充。

function setWidth() {
  var one = document.getElementById("one");
  var two = document.getElementById("two");
  var leftPadding = window.getComputedStyle(one, null).getPropertyValue('padding-left');
  var width = window.getComputedStyle(one, null).getPropertyValue('width');

  two.style.width = width;
  two.style.padding = leftPadding;
}

这是一个JSFiddle

我的代码将使用 class 'js-equal-width' 找到所有元素的最大宽度,并将所有元素设置为相同的宽度。

$(function() {
    const extraWidth = 50
    var maxWidth = 0
    $('.js-equal-width').each(function() {
        maxWidth = maxWidth > $(this).width() ? maxWidth : $(this).width()
    })

    $('.js-equal-width').each(function() {
        $(this).width(maxWidth + extraWidth)
    })
})

您可以使用 'js-equal-width'

<div style="width: 300px;">
     <span class="js-equal-width">Midterm Examination</span>
     <span class="js-equal-width">Final Examination</span>
</div>