gpt4 book ai didi

javascript - 在 jQuery 中计算百分比

转载 作者:行者123 更新时间:2023-12-01 01:42:46 24 4
gpt4 key购买 nike

我正在尝试根据 div 中的子级计算宽度百分比,但由于某种原因,它无法按预期工作。

$.each($("div.row"), function(index) {
let c = $(this).find("div.col").length;

if (c <= 12) {
let p = parseInt(c) / parseInt(12) * 100;

console.log({
count: c,
perc: p,
one: c / 12
});

$(this).find("div.col").css("width", p.toString() + "%");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- begin snippet: js hide: false console: true babel: false -->

<div class="row">
<div class="col">COL 1</div>
<div class="col">COL 2</div>
<div class="col">COL 3</div>

</div>

但我得到了一些意想不到的结果。如果 .row 包含 3 个 .col 元素,我期望获得大约 33%,因此这些元素填充父元素,但它返回 25。

我认为这应该相当容易......我做错了什么还是有其他方法可以做到这一点?

最佳答案

只需更改行 let p = parseInt(c) / parseInt(12) * 100;p = 100/parseInt(c)等宽

$.each($("div.row"), function (index) {
let c = $(this).find("div.col").length;

if (c <= 12) {
let p = 100/parseInt(c);

console.log({ count: c, perc: parseInt(p), one: c / 12 });

$(this).find("div.col").css("width", p.toString() + "%");
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="row">
<div class="col">COL 1</div>
<div class="col">COL 2</div>
<div class="col">COL 3</div>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>
</body>
</html>

关于javascript - 在 jQuery 中计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268692/

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