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(),但是找不到任何有用的东西。
4 个解决方案
#1
11
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在按钮单击时展开。
#2
1
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!
我希望这可以帮助!
#3
1
width: 100%;
display: block;
Optional:
可选:
position: absolute;
#4
-1
I think you can solve this using css width 100%
我认为你可以用css宽度100%来解决这个问题
div#full{ width:100%}
:)
:)
#1
11
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在按钮单击时展开。
#2
1
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!
我希望这可以帮助!
#3
1
width: 100%;
display: block;
Optional:
可选:
position: absolute;
#4
-1
I think you can solve this using css width 100%
我认为你可以用css宽度100%来解决这个问题
div#full{ width:100%}
:)
:)