【问题标题】:Make height same as dynamic width using JavaScript didn't work使用 JavaScript 使高度与动态宽度相同不起作用
【发布时间】:2016-10-14 06:11:37
【问题描述】:

我在我的项目中使用 Bootstrap 并尝试从 Bootstrap col 制作一个正方形,但它不起作用,并且它的宽度大小和高度大小总是不同的差距,例如 94.11px 和 94px。

我想让比例为 1:1 宽度:高度。但没用

HTML

<div class="content_image col-xs-3 squarethis"></div>
<div class="content_description col-xs-9 followheight"></div>

JavaScript

var st = $('.squarethis').width();
$('.squarethis').css({'height':st+'px'});
$('.followheight').css({'height':st+'px'});

有人知道吗?

var st = $('.squarethis').width();
$('.squarethis').css({'height':st+'px'});
$('.followheight').css({'height':st+'px'});
.squarethis{
width:30%;
  float:left;
background:#ccc;}
.followheight{
width:70%;
  float:left;
background:#999;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="squarethis">asd</div>
<div class="followheight">asd</div>

下图

the gap between width and height from this code

【问题讨论】:

  • 究竟是什么“不起作用”
  • 它的宽度和高度尺寸之间存在差距,例如 94.11 像素和 62 像素。 @Rayon
  • 你能分享一个例子/小提琴吗?
  • @Rayon 我不能总是显示“消息”:“未捕获的 ReferenceError:$ 未定义”,当我把它放在 JsFiddle 中时
  • 在使用时包含 jQuery 库;)

标签: javascript html twitter-bootstrap css height


【解决方案1】:

.css方法的回调中设置元素的height(.css( propertyName, function ))

更新: 经过几次测试,我可以确定,当 width 被分配给元素时,我们也会在页面上看到滚动条,这会导致变化在元素的width 中,正如我们在% 中分配它一样,设置overflow : hidden 会给你预期的结果!

$('.squarethis').css({
  'height': function() {
    return $(this).width()
  }
}).text(function() {
  return $(this).width() + ' x ' + $(this).height();
});
$('.followheight').css({
  'height': function() {
    return $(this).width()
  }
}).text(function() {
  return $(this).width() + ' x ' + $(this).height();
});
* {
  padding: 0;
  margin: 0;
}
body {
  overflow: hidden;
}
.squarethis {
  width: 30%;
  float: left;
  background: #ccc;
}
.followheight {
  width: 70%;
  float: left;
  background: #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="squarethis">asd</div>
<div class="followheight">asd</div>

Fiddle Demo

【讨论】:

  • 感谢您的努力,但它没有回答我的问题。如果您可以检查 squarethis div,您将看到它的宽度大小和高度大小的不同。它不是方形的
  • @riverrhun 什么不是?你在开玩笑吗?
  • 它不工作,我不行,我正在使用显示 flex 和调整中心,溢出隐藏在 .squarethis div 中,但它没有改变,仍然不是正方形。
  • 我检查了你更新的小提琴,它不是。谢谢你的努力。你可以检查 div 对吗?你会看到 'number'x'number' 定义了 div 的宽度和高度,它是不同的数字
  • @riverrhun 我可以.. 差异大约为 0.4 px.. 当单位为 px 时,我们真的不考虑浮点数吗?
猜你喜欢
  • 2017-03-14
  • 2021-08-25
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
  • 2018-12-29
  • 1970-01-01
  • 2018-03-03
相关资源
最近更新 更多