简体   繁体   English

计算并设置某些div的高度(初始设置)。 当浏览器窗口的高度改变时->更改div的高度

[英]calculate and set the height for some div (initial settings). When the height of the browser window is changed --> change the height for div

I need calculate and set the height for some div (initial settings). 我需要计算并设置一些div的高度(初始设置)。 When the height of the browser window is changed --> change the height for div. 当浏览器窗口的高度更改时->更改div的高度。

How will be better to rewrite this code (I want do initial settings once and change it when window resize): 如何更好地重写此代码(我想一次进行初始设置,并在调整窗口大小时进行更改):

$(document).ready(function () {
    var height = document.documentElement.clientHeight - 500;
    if (height < 135) {
        height = 135;
    }
    document.getElementById('left_space').style.height = height + 'px';

    $(window).resize(function () {
        var height = document.documentElement.clientHeight - 500;
        if (height < 135)
        {
            height = 135;
        }
        document.getElementById('left_space').style.height = height + 'px';
    });
});

is that what you are looking for? 那是您要找的东西吗?

api.jquery.com api.jquery.com

jQuery(document).ready(function () {

$(window).resize(function() {
   var height = document.documentElement.clientHeight - 500;
    if (height < 135) {
        height = 135;
    }
    document.getElementById('left_space').style.height = height + 'px';

    jQuery(window).resize(function () {
        var height = document.documentElement.clientHeight - 500;
        if (height < 135)
        {
            height = 135;
        }
        document.getElementById('left_space').style.height = height + 'px';
    });

});


});

If you are purely looking to tidy up the code, it could look something like this: 如果您纯粹是想整理一下代码,它可能看起来像这样:

$(document).ready(function () {

    var resizeIt = function() {
      var height = Math.max(document.documentElement.clientHeight - 500, 135);
      $('#left_space').css('height', height + 'px');
    };

    resizeIt();

    $(window).resize(function () {
        resizeIt();
    });
});

Here I have pulled out the lines of code that set the height into their own function, so the code is not duplicated. 在这里,我已经摘录了将高度设置为自己的函数的代码行,因此这些代码不会重复。 Then I took advantage of some of the shorter syntax you can use in jQuery for finding and changing styles of elements. 然后,我利用了可以在jQuery中使用的一些较短的语法来查找和更改元素的样式。

我认为jQuery(window).resize一个会很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM