使用 jQuery 实时更改 div 宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8153281/
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
Change div width live with jQuery
提问by Alex
Is it possible to change a div
's width live with jQuery? And if it is, how?
是否可以div
使用 jQuery 实时更改 a的宽度?如果是,如何?
What I want is to change its width depending on the browser's window width in real time, so if/when the user changes the browser window, the div
's dimensions are changed as well in realtime.
我想要的是根据浏览器的窗口宽度实时更改其宽度,因此如果/当用户更改浏览器窗口时,div
的尺寸也会实时更改。
回答by Niels
You can use, which will be triggered when the window resizes.
您可以使用,它会在窗口调整大小时触发。
$( window ).bind("resize", function(){
// Change the width of the div
$("#yourdiv").width( 600 );
});
If you want a DIV width as percentage of the screen, just use CSS width : 80%;
.
如果你想要一个 DIV 宽度作为屏幕的百分比,只需使用 CSS width : 80%;
。
回答by Rory McCrossan
It is indeed possible to change a div
elements' width in jQuery:
确实可以div
在 jQuery 中更改元素的宽度:
$("#div").css("width", "300px");
However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:
但是,通过将宽度设置为百分比,可以在 CSS 中更好、更有效地实现您所描述的内容:
#div {
width: 75%;
/* You can also specify min/max widths */
min-width: 300px;
max-width: 960px;
}
This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.
这个 div 将始终是屏幕宽度的 75%,除非屏幕宽度意味着 div 将小于 300 像素或大于 960 像素。
回答by Deviprasad Das
There are two ways to do this:
有两种方法可以做到这一点:
CSS:Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.
CSS:使用宽度作为 %,比如 75%,这样当用户调整浏览器大小时 div 的宽度会自动改变。
Javascipt:Use resizeevent
Javascipt:使用调整大小事件
$(window).bind('resize', function()
{
if($(window).width() > 500)
$('#divID').css('width', '300px');
else
$('divID').css('width', '200px');
});
Hope this will help you :)
希望这会帮助你:)
回答by calmburst
Got better solution:
得到了更好的解决方案:
$('#element').resizable({
stop: function( event, ui ) {
$('#element').height(ui.originalSize.height);
}
});
回答by Nate B
You can't just use a percentage width for the div
? Setting the width to 50% will make it 50% as wide as the window (assuming there is no parent element with a width assigned to it).
您不能只对div
? 将宽度设置为 50% 将使其宽度为窗口的 50%(假设没有为其分配宽度的父元素)。