【问题标题】:Link two HTML divs' dimensions to each other?将两个 HTML div 的尺寸相互链接?
【发布时间】:2014-06-04 20:10:30
【问题描述】:

如果我有 div A 和 div B,有没有办法说 A.width = b.width = MAX(a.width, b.width) ?也就是说,无论哪个具有最大的内部内容,都将决定两者的大小。

我要解决的实际问题是列 - leftmiddleright。我希望左右是相同的固定宽度(但这可能会因它们的内容而异)。

【问题讨论】:

  • 使用css3柔性盒有什么问题吗?

标签: javascript jquery html css layout


【解决方案1】:

从描述中不太清楚你想要什么。但我可以这样重写你的代码。

  var properWidth = Math.max($("#a").width(), $("#b").width());
  $("#a").css("width", properWidth + "px");
  $("#b").css("width", properWidth + "px");

我不确定是不是你想要的这种解决方案。

【讨论】:

  • 嗯,这可能是最好的解决方案。有没有办法隐含地做到这一点?如果 b 稍后发生变化?
  • @xtravar 这将是 JavaScript (jQuery),因此每当您的一个 div 的大小发生变化时都必须调用它。
【解决方案2】:

不可能使用 CSS 来实现这一点。但是,如果有办法使用基于 JS 的解决方案来做到这一点。这里我使用 jQuery。假设您有两个 div,类分别为 ab

$(function() {
    function equalizeSize($ele) {
        if($ele.length > 1) {
            // Let CSS automatically calculate natural width first
            $ele.css({ width: 'auto' });

            // And then we fetch the newly calculated widths
            var maxWidth = Math.max.apply(Math, $ele.map(function(){ return $(this).outerWidth(); }).get());
            $ele.css({ width: maxWidth });
        }
    }

    // Run when DOM is ready
    equalizeSize($('.a, .b'));

    // Run again when viewport has been resized, which **may** affect your div width.
    // This is optional, but good to have
    // ps: You might want to look into throttling the resize function
    $(window).resize(equalizeSize($('.a, .b')));
});

在此处查看概念验证小提琴:http://jsfiddle.net/teddyrised/N4MMg/

这个简单函数的优点:

  1. 允许您指定要使用哪些元素来均衡宽度。
  2. 使用.map()函数构造一个数组,然后我们使用Math.max.apply获取数组中的最大值
  3. 在函数首次触发时强制自动计算宽度(尤其是在调整视口大小时)
  4. 允许您在更改 div 中的内容时使用处理程序 equalizeSize() 再次调用以重新计算大小...您可以再次调用该函数,例如,在将内容附加到任一元素的 AJAX 调用之后。

【讨论】:

  • 这真的很酷,并且回答了我的很多问题。 width() 返回的值似乎不正确(按单位或其他方式)。我会继续玩它的。编辑:更改为 outerWidth() 并且代码有效。这是预期的吗?
  • 是的,确实有道理,尤其是当您为 <div> 声明了 box-sizing: border-box 并且它们的样式中有填充时。
【解决方案3】:

我不确定有没有办法做到这一点。但是为什么不做一个默认的函数来设置大小:

function changeSize(w, h)
{
    A.setAttribute('style', 'width:'+w+'; height:'+h);
    b.setAttribute('style', 'width:'+w+'; height:'+h);
}

工作小提琴:http://jsfiddle.net/kychan/ER2zZ/

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 1970-01-01
    • 2016-03-18
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多