JQUERY:将 div 调整为窗口宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8095554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQUERY: Resize div to window width
提问by Guy
I am trying to force the width of a div to the width of a browser window. So that even if the window is resize the adjusts it's width.
我试图将 div 的宽度强制为浏览器窗口的宽度。这样即使窗口调整大小也会调整它的宽度。
I have been researching for about an hour and have found odd bits and pieces such as .resize() but can't find anything which works.
我已经研究了大约一个小时,发现了一些奇怪的东西,比如 .resize() ,但找不到任何有效的东西。
回答by James Johnson
Without a container limiting the width, a div should span the width of the browser window by default. You can explicitly set the width to 100%, but that shouldn't be necessary:
如果没有容器限制宽度,默认情况下 div 应该跨越浏览器窗口的宽度。您可以明确地将宽度设置为 100%,但这不是必需的:
<div style="width:100%;">Hello world</div>
I think CSS is more appropriate here, but you can do this in jQuery like this:
我认为 CSS 在这里更合适,但你可以在 jQuery 中这样做:
$("#div1").width($(window).width());
To run the above code whenever the window is resized, you can do this:
要在调整窗口大小时运行上述代码,您可以执行以下操作:
$(window).resize(function(){
$("#div1").width($(window).width());
});
Here's a jsFiddle. For the sake of demonstration, the div expands on button click.
这是一个jsFiddle。为了演示,div 在按钮点击时展开。
回答by dSquared
Try this:
尝试这个:
<div id="full"></div>
<script type="text/javascript">
function reSize($target){
$target.css('width', $(window).width()+'px');
}
$(document).ready(function(){
$(window).bind('resize', reSize($('#full')));
$(window).trigger('resize');
});
</script>
I hope this helps!
我希望这有帮助!
回答by Charlie Brown
width: 100%;
display: block;
Optional:
可选的:
position: absolute;
回答by Martin Borthiry
I think you can solve this using css width 100%
我认为你可以使用 css width 100% 解决这个问题
div#full{ width:100%}
:)
:)