gpt4 book ai didi

jquery - 获取一行中列的宽度

转载 作者:行者123 更新时间:2023-11-28 10:24:30 26 4
gpt4 key购买 nike

我正在尝试为我的网站制作一个栏目系统,它看起来像这样:

<div class="container">
<div class="row">
<div class="col-13">a</div>
<div class="col-13" style="background-color: yellow;">a</div>
<div class="col-13">a</div>
</div>
</div>

它在 CSS 中的样子:

.container {
width: 75%;
clear: both;
margin: 0 auto;
}
.row {
margin-bottom: 40px;
overflow: hidden;
}
div[class*="col-"] {
float: left;
min-height: 1px;
}
.col-13 {
width: 33.333333%;
background-color: blue;
}

现在我试图在 jQuery 中创建一个简单的系统,当一个 <div class="row">其中有列( <div class="col-13"> etc. etc. etc. )它的 width大于 100%。该行未显示。

所以首先我必须找到行内列的所有宽度。我通过这段代码尝试过:

$('.row div[class*="col-"]').each(function(index) {
var _this = $(this);
var width = _this.width();
var parentWidth = _this.offsetParent().width();
var percent = Math.round(100*width/parentWidth);
console.log('The elements width is '+percent+'%');
});

但是当我尝试使用这段 html 代码时:

<div class="row">
<div class="col-13">a</div>
<div class="col-13" style="background-color: yellow;">a</div>
<div class="col-13">a</div>
</div>

预期输出
3x 33.333333% , 因为我有 3x 个 <div class="col-13"> 的元素它有一个 width33.333333% .

实际输出
3x 25% ,我猜是因为 .container宽度为 75%它正在计算那个,但我不知道为什么。

之后我想计算它,但我不知道该怎么做。

Demo

最佳答案

改变

var parentWidth = _this.offsetParent().width();

var parentWidth = _this.parent().width();

这是因为offsetParent()将在祖先中搜索第一个定位的祖先。在您的示例中,这将返回 html 元素,据我所知。

parent() ,没有指定的选择器,将返回最近的父元素。在您的示例中,这将返回 .row

关于jquery - 获取一行中列的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com