Get width of specific div and use as another div&#

2019-08-30 20:27发布

I have two div's. #divA & #divB.

#divA has a width of 100% and I want to get the px value of the div and apply it to #divB as it's height CSS. I've tried using .offsetWidth but to no avail. Can anybody help me?

2条回答
仙女界的扛把子
2楼-- · 2019-08-30 21:06

use .css('width') to keep units intact (ex: 400px), use .width() to get just the numerical value (ex: 400) for use in mathematical computations.

for what you're doing:

var divAWidth = $('#divA').css('width');
$('#divB').css('height', divAWidth);

if you're getting mathematical:

var divAWidthNumber = $('#divA').width();
var halfThatWidth = divAWidthNumber / 2;
查看更多
虎瘦雄心在
3楼-- · 2019-08-30 21:07

If you don't want to use jQuery:

var getwidth = document.getElementById("div1").style.width;
document.getElementById("div").style.height = getWidth;

With jQuery

var getwidth = $("#div1").width();

EDIT

$("#div").height(getwidth);
查看更多
登录 后发表回答