douzhi9635 2015-10-29 18:04
浏览 46

PHP:使用十进制值添加div背景颜色(1 =黑色,0 =白色)

So in my gaming system after I query the players database, I get a value between from 0 to 1. 0 should represent white and 1 should represent black. 0.01 to 0.99 represents the shades from white to black.

I use the gaming data to show the players profile details on a webpage.

How can I dynamically create a logic to generate the color code based on this decimal value? I need to make the background color of the div of each player a shade of grey as represented by the player's orientation number (0 to 1)

I tried to add background-color:black to the div and then reduce opacity to simulate change in shade. Unfortunately this also makes the content inside the div transparent too. I tried adding opacity:1 to inside div but it did not work.

So I think finding a way to convert the decimal value to a hex value between black and white must be the way.

Any insight is greatly appreciated!

  • 写回答

3条回答 默认 最新

  • duanbi3786 2015-10-29 18:11
    关注

    The colors are expressed in RGB (Red, Green, Blue) with each value ranging between 0 and 255, so simply multiply your value by 255 for each color component and then set your div's background color like this:

    <div id="myDiv">This is a color test</div>
    
    <script>
      var value = 0.1;
      var color_component = Math.ceil(255 * (1 - value));
      var color = "rgb(" + color_component + "," + color_component + "," + color_component + ")";
      document.getElementById("myDiv").style.backgroundColor = color;
    </script>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!