最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JQueryJavascript for Div auto resizing when browserwindow resize - Stack Overflow

programmeradmin2浏览0评论

I have only 1 div and what I want is that when browser resize, the height and width of the div will auto resize. For example, I pull the browsers height downward, then the height of the div, will also increases and when I pull the width of the browser, then the div's width will also increases. And vice versa, when the browser shrink/decreases its width and height, the div will also do the same.

/

$(window).resize(function(){ // On resize
       $("#mydiv").css('height','+=1px','width','+=1px');
});
#mydiv{
  border: solid 2px #3675B4;
  height:300px
}
<script src=".0.3/jquery.min.js"></script>
<div id = "mydiv">

</div>

I have only 1 div and what I want is that when browser resize, the height and width of the div will auto resize. For example, I pull the browsers height downward, then the height of the div, will also increases and when I pull the width of the browser, then the div's width will also increases. And vice versa, when the browser shrink/decreases its width and height, the div will also do the same.

https://jsfiddle/koykoys/eghL1cjp/2/

$(window).resize(function(){ // On resize
       $("#mydiv").css('height','+=1px','width','+=1px');
});
#mydiv{
  border: solid 2px #3675B4;
  height:300px
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id = "mydiv">

</div>

Share Improve this question asked Aug 14, 2016 at 2:54 RockyRocky 1374 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You should use css instead of javascript.

use following class

#mydiv{
  border: solid 2px #3675B4;
  height:100vh;
  width:100vw;
}

Updated Fiddle

vh stands for viewport-height and vw is viewport-width

So your div is getting height:100vh; means 100% of viewport height and width:100vw; means 100% of viewport width

Read more about viewport units in detail

Update -

You should avoid using JS for this but for some reason if you have to.

This should work

var resize = function() {
  var windowWidth = $(window).width();
  var windowHeight = $(window).height();
    console.log(windowWidth)
    console.log(windowHeight)
    $("#mydiv").css({
    "height": windowHeight + "px",
    "width": windowWidth + "px",

  });

  }
$(document).ready(resize);
$(window).on("load resize", resize);

Updated Fiddle

发布评论

评论列表(0)

  1. 暂无评论