简体   繁体   English

根据浏览器窗口的宽度(以jQuery或JS为单位)设置div的高度(以像素为单位)

[英]Set height of div in pixels based off width of browser window in % (jQuery or JS?)

I am trying to set up a black border around a webpage. 我正在尝试在网页周围设置黑色边框。 For the left and right side, just making "width: 5%;" 对于左侧和右侧,仅制作“宽度:5%;” in the CSS is fine. 在CSS中就可以了。 But then I want JS/jQuery to work out how many pixels that is, and make that the height of the top and bottom div. 但是然后我想让JS / jQuery计算出多少个像素,并使其成为top和bottom div的高度。

Is this possible? 这可能吗?

Thanks. 谢谢。

This should work for you 这应该为你工作

var val = $(".leftAndRight").width();
$(".topAndBottom").height(val);

Or with one line: 或一行:

$(".topAndBottom").height($(".leftAndRight").width());

You can determine the value for the border width programmatically, assign it to all four borders, and also refresh it any time you resize: 您可以通过编程确定边框宽度的值,将其分配给所有四个边框,并在每次调整大小时刷新它:

var width,
    drawBorder = function () {
        var body = $('body'),
            width = body.width() * 0.05;
        body.css('border-width', width + 'px');
    };

drawBorder();

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

Demo 演示

If you set the left and right width in your stylesheet and then use JS to give the same border width to the top and bottom, unless you use a resize function your left and right borders will change every time you resize but your top and bottom borders will remain fixed. 如果您在样式表中设置左右宽度,然后使用JS为顶部和底部赋予相同的边框宽度,除非您使用了resize功能,否则每次调整大小时,左右边框都会改变,但是上下边框将保持不变。

You can use .width() to find width without the border and .outerWidth to find the width including the border. 您可以使用.width()查找不带边框的宽度,并使用.outerWidth查找包含边框的宽度。 I think .outerWidth also gives you the width with the padding you may have to subtract that. 我认为.outerWidth还为您提供了可能需要减去的填充宽度。

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

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