[英]Background should adapt to content height using JQuery on window resizing
The content of a div will be set dynamically. div的内容将动态设置。 The div #background, should adapt to the height that (separate) div will have. div #background应该适应(单独)div所具有的高度。 The background also should adapt to resizing of the div when the browser is resized. 在调整浏览器大小时,后台还应该适应div的大小调整。 So the action should happen when the page loads , or when the browser is resized . 因此, 当页面加载或调整浏览器大小时 ,操作应该发生。
<div id="wrapper">
<div id="background"></div>
<div id="content">
<p>This content will be set dynamically.
<br>The div #background should adapt to this height.
<br><br><br><br><br><br>
<br>This should happen when the page loads,
<br>or when the browser is resized.
<br>At this moment, it only works when
<br>the page loads.
<br>
</p>
<!-- end #content -->
</div>
<!-- end #wrapper -->
At this moment, it only works when the page loads eventhough I added this code: 此时,它仅在页面加载时才起作用,尽管我添加了以下代码:
$(window).resize(function () {
$("#background").css({
height: ($("#wrapper").height() + 50) + 'px'
});
});
How can I get the resizing bit working? 如何让调整大小的位工作? Thanks. 谢谢。
Your resize
handler is working as intended, but the issue is that #wrapper
won't change height unless you give it height, so right now you're simply updating the height
on #background
to the same value each time resize
is fired: 您的resize
处理程序正在按预期工作,但问题是#wrapper
不会更改高度,除非您给它高度,所以现在您只需在每次resize
将#background
上的height
更新为相同的值:
$(window).resize(function () {
$("#background").css({
height: ($("#wrapper").height() + 50) + 'px'
// ^^^^^^^^^^^^^^^^^^^^^^ this value never changes
});
});
Here's an updated demo where I've added 这是我添加的更新演示
html, body, #wrapper { height: 100%; }
You should use .on()
: 你应该使用.on()
:
$(window).on("resize load", function () {
$("#background").css({
height: ($("#wrapper").height() + 50) + 'px'
});
});
does that work for you? 那对你有用吗?
Trigger it on load. 在加载时触发它。
$(window).resize(function () {
$("#background").css({
height: $("#wrapper").height() + 50
});
}).trigger("resize");
http://api.jquery.com/trigger/ http://api.jquery.com/trigger/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.