【问题标题】:How to calculate relative percent to total?如何计算相对百分比?
【发布时间】:2020-12-23 04:56:57
【问题描述】:

我正在尝试创建一个基于总百分比的字体大小的词云。每个单词都有一个“count”属性。

<h2>Cryptos</h2>
<div class="topics">
{#each cryptos as topic}
    <a
    href="/cryptos/{topic._id}"
    style="font-size: {(topic.count / topics[0].count) * 100 + 100}%;">${topic._id}
    ({topic.count})</a>
{/each}
</div>

这不太正常,我不知道为什么。

font-size: {(topic.count / topics[0].count) * 100 + 100}%;

主题按照.count降序排列

我基本上希望字体大小在低端为 100%,在高端为 200%。

【问题讨论】:

  • 您的代码正在生成哪些font-size 值?
  • 表面看来是正确的。在这种情况下,“工作不正常”到底是什么意思?
  • 我买了一个大的,其他的都一样。
  • font-size: 107.xxx% 对于大多数标签。
  • @chovy 有多少字/计数?因为如果有 14 个单词并且每个单词的计数为 1,那么 107.xx% 似乎是正确的。

标签: javascript html math svelte


【解决方案1】:

可以通过比较字体大小范围和字数范围来改变字体大小。

假设您有一个单词列表及其数量:

const words = [
  { text: "apples", count: 10 },
  { text: "pears", count: 30 },
  // ...
]

可以计算font-size的范围:

const minFontSize = 10
const maxFontSize = 30

// delta between sizes
const fontRange = maxFontSize - minFontSize

然后计算最小字数、最大字数和字数范围。反应式语句对此很有效:

// list of counts
$: counts = words.map(record => record.count)

// minimum word count
$: min = Math.min(...counts)

// maximum word count
$: max = Math.max(...counts)

// delta between smallest and largest word count
$: countRange = max - min

现在我们可以计算字体大小了:

minFontSize + (deltaWordCount * sizeRatio)

或者更具体地说:

{#each words as word}
  <span style="font-size: {minFontSize + ((word.count - min) * (fontRange / countRange))}px">
    {word.text}
  </span>
{/each}

您可以在这里找到一个工作示例:https://svelte.dev/repl/770e4a35186449a182b8edecc4ed88ba?version=3.31.0

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2013-11-14
    • 2021-05-26
    • 1970-01-01
    • 2011-06-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多