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

如何实现公司股价涨跌幅百分比展示及正负值红绿配色效果?

我们需要对原有代码中涨跌幅的处理逻辑做如下调整,即可实现需求:

  • 先将接口返回的涨跌幅字段转换为纯数字,剔除可能存在的%、括号等冗余字符,避免判断出错
  • 使用toFixed(2)方法保留两位小数后拼接%符号,完成百分比格式展示
  • 新增正负值判断:数值小于0时设置字体为红色,大于等于0时设置为绿色

修改后的完整代码如下:

// 拉取公司简介数据
const companyTitle = document.getElementById("company-title");
const companyLogo = document.getElementById("company-logo");
const price = document.getElementById("price");
const companyDescription = document.getElementById("company-description");
const changesPercentage = document.getElementById("changesPercentage");

const symbol = window.location.search.replace("?symbol=", "");

if (symbol) {
  getCompanyProfile(symbol);
} else {
  alert("未传递股票代码参数");
}

function getCompanyProfile(symbol) {
  const url = `https://appspot.com/api/v3/company/profile/${symbol}`;
  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      const profile = data.profile;
      companyTitle.textContent = profile.companyName;
      companyDescription.textContent = profile.description;
      price.textContent = "股票价格:$" + profile.price;

      // 涨跌幅格式化与颜色设置逻辑
      // 提取纯数值,兼容接口可能返回的带%/括号的格式
      const changeVal = parseFloat(profile.changesPercentage.toString().replace(/[^\d.-]/g, ''));
      // 保留两位小数,拼接%完成格式转换
      const formatChange = changeVal.toFixed(2) + '%';
      changesPercentage.textContent = formatChange;
      // 按正负设置对应颜色
      changesPercentage.style.color = changeVal < 0 ? '#ff0000' : '#00b578';

      // 设置公司logo
      let img = document.createElement("img");
      img.src = profile.image;
      companyLogo.appendChild(img);
      console.log(data);
    })
    .catch((err) => {
      console.warn("请求出错", err.message);
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:21:02