简体   繁体   English

将元素的宽度(或高度)设置为较高祖先元素的百分比

[英]Set width (or height) of element as percentage of higher ancestor element

If I have a DOM structure with three DIVs A, B & C where C is a child of B; 如果我有一个带有三个DIV A,B和C的DOM结构,其中C是B的子级; and B is a child of A - is there a way to set the width (or height) of C to be a percentage of the width (or height) of A? 和B是A的孩子 - 有没有办法将C的宽度(或高度)设置为A的宽度(或高度)的百分比?

PS: jQuery is available, and any jQuery functionality can be used. PS:jQuery可用,可以使用任何jQuery功能。

那么,在这种情况下,请尝试$('#c').height( $('#c').parent().parent().height() * pct/100 )

If it has to be calculated once only (no resize problems), just fetch the height of A and set the height of C accordingly. 如果必须只计算一次(没有调整大小问题),只需获取A的高度并相应地设置C的高度。

var heightA = $('#divA').height();
var heightC = heightA * 0.50; // 50%
$('#divC').height(heightC);

Try this 尝试这个

$(function(){
   var height = $("#A").height();
   var width = $("#A").width();
   $("#c")
   .width(width * 0.10);//10%, you can set whatever percent you need
   .height(height * 0.10);//10%, you can set whatever percent you need
});

This would work: 这可行:

var height_A = $('#div_A').height();
var width_A = $('#div_a').width();
$('#div_C').height(height_A*0.30); // for 30%
$('#div_C')width(width_A*0.30);  // for 30%

Assuming A's parent has no width defined and A and B can't be width:100% for a much more lightweight and sensible CSS solution: 假设A的父级没有定义宽度,A和B不能是宽度:100%,对于更轻量级和更敏感的CSS解决方案:

$('#divC').height( $('#divA').height() * (percentage/100) );

If this is for a real-world problem, it's a bad solution. 如果这是一个现实世界的问题,这是一个糟糕的解决方案。 Never solve layout problems with the JS-hammer. 永远不要用JS-hammer解决布局问题。

The following would be ideal. 以下是理想的。

#parent_of_a { width:<anything>; }
#a, #b { width:100%; }
#c { width:<whatever>% };

CSS % width requires that an element's parent's width is defined. CSS%width要求定义元素​​的父宽度。

Try this: 尝试这个:

$(function(){
   var aheight = $("#a").height();
   var awidth = $("#a").width();
   $("#c").width(awidth * 0.50).height(aheight * 0.50);
});

You shouldn't solve layout issues with JavaScipt, since JS can be disabled. 您不应该使用JavaScipt解决布局问题,因为可以禁用JS。 That being said... 话虽如此...

This code should work even if the window is resized. 即使调整窗口大小,此代码也应该有效。

function setDimension() {
    var containerWidth = $('#divC').parent().parent().width();
    $('#divC').width(containerWidth * 0.5);
}

$(setDimension); // do it on initial load
$(window).resize(setDimension); // do it when window is resized

HTML width supports percentages. HTML width支持百分比。 I don't see how you'd need to do anything special to make it work. 我不知道你怎么需要做任何特别的事情才能让它发挥作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM