You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中获取精确百分比?数据库数据转高度百分比公式求助

Correct JavaScript Formula for Reverse Linear Mapping to Div Height Percentages

First, let's break down the required relationship to nail the right formula:

  • When the data value is 10, we need an output of 100% (full div height)
  • When the data value is 65, we need an output of 0% (no height)

This is a reverse linear mapping—higher input values translate to lower percentage heights. Here's how to derive the formula step by step:

  1. The total range of input values is 65 - 10 = 55 (the span between our min and max trigger points).
  2. To get the percentage, we calculate how far the input is from the maximum value (65) relative to this range, then multiply by 100.

The simplified formula is:

percentage = 100 * (65 - inputValue) / 55;

Let's verify it works for our edge cases:

  • For input = 10: 100*(65-10)/55 = 100*55/55 = 100% ✔️
  • For input = 65: 100*(65-65)/55 = 0% ✔️
  • For a middle value like 37.5: 100*(65-37.5)/55 = 100*27.5/55 = 50% ✔️ (perfect midpoint checks out)

Modified Code Implementation

Here's how to update your existing code with this correct logic:

var datas = JSON.parse(data);
var ID, Bio, Non_Bio, Recy, Extra;

// Extract data values (fixed a typo in the Extra line)
ID = datas[0].ID;
Bio = datas[0].Bio;
Non_Bio = datas[0].Non_Bio;
Recy = datas[0].Recy;
Extra = datas[0].Extra;

// Calculate percentage heights using the reverse linear formula
var obt = 100 * (65 - Bio) / 55;
var obt2 = 100 * (65 - Non_Bio) / 55;
var obt3 = 100 * (65 - Recy) / 55;

// Apply the percentage to the divs (standard way to set percentage-based height in CSS)
$("#water1").css('height', obt + '%');
$("#water2").css('height', obt2 + '%');
$("#water3").css('height', obt3 + '%');

// If you intended to add a percentage-based value to the existing height (not set it directly), use this instead:
// var parentHeight = $("#water1").parent().height();
// var water1 = $("#water1").height() + (parentHeight * obt / 100);

Quick Notes:

  • Fixed a typo in Extra = datas[0]. Extra; (removed the extra space after the dot)
  • Your original code was adding the calculated value directly to the height as pixels, which is almost certainly not what you want for percentage-based div heights. The updated code sets the CSS height directly as a percentage string, which is the standard approach.

内容的提问来源于stack exchange,提问作者john

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:17:26