简体   繁体   English

根据另一个div设置DIV的宽度和高度

[英]Set width and height of a DIV based on another div

How do I set width and height of a DIV based on another div? 如何根据另一个div设置DIV的宽度和高度?

This is how I've done it but it works only when the alert is present?? 这是我的操作方式,但仅在出现alert时有效?

var readyC = setInterval(function() {
  if (Condition) {
    $('#divAA').width($('#divBB').width()).height($('#divBB').height()); 
          //alert($('#divBB').width())  // works when this is uncommented?? 
  }
  clearInterval(readyC);
}, 10);

EDIT: 编辑:

Fixed typo: 固定错别字:

$('#divBB'+i) to $('#divBB') $('#divBB'+i)$('#divBB')

If the content of your divs are loaded dynamically, then you will need to use window.load event to get its correct height as discussed here: https://stackoverflow.com/a/13071846/1845408 如果div的内容是动态加载的,那么您将需要使用window.load事件来获取其正确的高度,如下所示: https : //stackoverflow.com/a/13071846/1845408

$(window).load(function() {
    $('#divAA').width($('#divBB').width()).height($('#divBB').height()); 
});

The reason why you're getting it only when you keep an alert is, you're using setInterval with such small interval of 10ms . 之所以仅在保持alert时才得到它,是因为您使用的setInterval间隔很小,为10ms

When you use alert, the execution is stopped and that's why you see the div resized. 当您使用alert时,执行将停止,这就是为什么div调整了大小的原因。 You must increase the interval to a higher value. 您必须将interval增加到更高的值。

Also clearInterval is not inside else block, So it means what the timer will clear on first attempt itself. 另外clearInterval不在else块内,因此这意味着计时器将在第一次尝试本身时清除。 In that case you don't need a setInterval at all. 在这种情况下,您根本不需要setInterval。

Update based on comments 根据评论更新

As you're looping through a list of divs to update the height of other divs, you must use self invoking function to bind the value of i correctly. 在遍历div列表以更新其他div的高度时,必须使用自调用函数正确绑定i的值。

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

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