Get width and height of screen window and height of div jquery

↘锁芯ラ 提交于 2019-12-11 18:33:10

问题


In plain English this is the jQuery functionality i'm after:

I need to get the width and the height of the browser window and then get the height of .banner div (height is automatic). If the height of .banner div is higher than that of the height of the browser window append .title div and .social div to the body otherwise display .title div and .social div within .banner div.

How do I then style the two divs accordingly (.title and .social)?

EDIT: This is my on page load code in HTML:

<div class="banner">
   <div class="title">
      <!--to be positioned 40px from the left-->
   </div>
   <div class="social">
      <!--to be positioned 40px from the right-->
   </div>

   <img src="URL"/> <!-- Image determines height of DIV uses max-width -->

</div>

回答1:


You can do something like below:

var windowHeight = $(window).height(); //Gives you the browser viewport height
var bannerHeight = $(".banner").height();

if (bannerHeight > windowHeight) {
    $("body").append($('.title'));
    $("body").append($('.social'));

    //Then you can style them using jQuery .css
    //Example
    $('.title').css('color', 'red');
}
else {
    //Display .title and .social in your .banner div
}
  • jQuery .height info: http://api.jquery.com/height/
  • jQuery .css info: http://api.jquery.com/css/



回答2:


Use these functions:

$(window).height();
$(window).width();
$('.banner').width();
$('.banner').height();
$("#tostyle").addClass('someclass');

etc




回答3:


update dynamicly the elements :

$(function(){
    var divheight = $('.banner').height(); // div current height

    // handle the resize event
    $(window).resize(function(){
        if($(this).height() < divheight) {
            $('.title').appendTo($('body'));
            $('.social').appendTo($('body'));
            $('.banner').hide();
        } else {
            $('.title').appendTo($('.banner'));
            $('.social').appendTo($('.banner'));
            $('.banner').show();
        }
    });
});

the code is deliberately not simplify for better readability



来源:https://stackoverflow.com/questions/10995356/get-width-and-height-of-screen-window-and-height-of-div-jquery

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