Change div width live with jQuery

℡╲_俬逩灬. 提交于 2019-12-18 14:29:11

问题


Is it possible to change a div's width live with jQuery? And if it is, how?

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.


回答1:


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%;.




回答2:


It is indeed possible to change a div elements' width in 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:

#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.




回答3:


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.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)




回答4:


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).




回答5:


Got better solution:

$('#element').resizable({
    stop: function( event, ui ) {
        $('#element').height(ui.originalSize.height);
    }
});


来源:https://stackoverflow.com/questions/8153281/change-div-width-live-with-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!