【问题标题】:How to make objects a percentage of the width of another如何使对象占另一个宽度的百分比
【发布时间】:2015-07-08 18:17:10
【问题描述】:

我正在尝试放置 3 个填充窗口宽度的 div,它们的 width 会根据窗口的尺寸而变化。然而javascript 似乎给出的窗口宽度大于它实际上导致对象流出窗口导致滚动。你可以在这里看到我的完整代码:http://jsbin.com/vifagazefu/3/edit?html,css,js,output

这是javascript:

 $(window).resize( setDim());

function setDim() {
    var windowWidth = $(window).innerWidth()- 3; //the 3 is for the 1px margin between the divs

  var windowHeight = $(window).innerHeight() - 70;

  $(".one").innerWidth(windowWidth / 3);
  $(".two").innerWidth(windowWidth / 3);
  $(".three").innerWidth(windowWidth / 3);

  $(".one").innerHeight(windowHeight);
  $(".two").innerHeight(windowHeight);
  $(".three").innerHeight(windowHeight);
}

setDim();

【问题讨论】:

  • 首先,它应该是$(window).resize(setDim); 而不是$(window).resize( setDim());。其次,为什么不使用 CSS 媒体查询?或者如果出于其他原因需要js,则改用widow.matchMedia方法
  • 为什么不在 CSS 中使用百分比? .one, .two, .three { width: 33%; }
  • 我正在做一个项目,其中我在另一个 div 中有 div。我希望这些内部 div 是窗口的百分比,而不是父窗口的百分比。
  • @A.Wolff 调用带括号和不带括号的函数有什么区别?
  • @CosX 如何全选? “*”是否适用于 css?

标签: javascript jquery height width


【解决方案1】:

只需输入 $(document.body).innerWidth()-3; 而不是 $(window).innerWidth()-3; 就可以了。这是因为 body 元素有边距并且它是由浏览器设置的,是的,您可以将 body 的边距重置为 0px,但我们为什么不更准确地计算 body。

这是使用 $(document.body).innerWidth()-3; http://jsbin.com/puqavufela/1/ 编辑的 bin
这是使用body {margin:0px} http://jsbin.com/somogusugo/1/编辑的bin

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 2013-07-26
    • 2018-10-15
    • 2020-10-17
    • 1970-01-01
    • 2013-04-01
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多