javascript - 使用javascript计算宽度并调整css

标签 javascript jquery css

我正在使用 javascript 计算 #red#yellow 的宽度和 css 来设计。 html 是:

<div id="gray">
   <div id="red"></div>
   <div id="yellow"></div>
</div>

<style>
  #gray {
    width:100px;
  }
  #red {
    background-color:red;
    float: left;
  }
  #yellow {
    background-color: yellow;
    float:left;
  }
</style>

宽度以填充#gray 颜色的百分比计算。直到#red#yellow 的宽度之和小于或等于100% 时显示才正确,因为我已经考虑过div #gray100% 宽度。如果总和超过 100%,则颜色条显示为两行。当总和超过 100% 时,是否可以计算 #gray 的宽度,以便条形排成一行,并且可以用虚线作为指示符,其中 100% width 是超过了。请问我是否不清楚我的意思。基本上我希望 #yellow#red 都在同一行,而不是一个在另一个下面

编辑:

config.hourPerPercent=parseInt(data.totalspace)/100;
var futureNum=new Number((1/config.hourPerPercent)*parseInt(data.inuse));
var recNum=new Number((1/config.hourPerPercent)*parseInt(data.used));

config.Usage=futureNum.toFixed(2);              
config.Used=recNum.toFixed(2);

$('#red').css('width',config.Used+'%');         
$('#yellow').css('width',config.Usage+'%');

宽度随着数据的变化而动态变化,每当数据有变化时计算。我在下面附上了三张图片,可以很容易地理解我的意思。对于第一张图片,因为宽度之和大于 100%,#yellow 低于 #red。绿色背景是#gray的宽度。我希望当宽度总和增加 100% 时 #yellow 不应低于 #red 而应该像第二张带有视觉指示的图像可能是虚线像第三张图片一样超过 100% 限制的点。希望这有助于解释我的问题。

This is the situation when sum of the width of <code>#red</code> and <code>#yellow</code> is greater then 100%

This is when sum of the width 0f <code>#red</code> and <code>#yellow</code> is equal to 100%

Final output display

最佳答案

<div id="gray">
   <div id="red"></div>
   <div id="yellow"></div>
</div>

jQuery 将放在 $(document).ready() 中

var w_red=$("#red").outerWidth(true);
var w_yellow=$("#yellow").outerWidth(true);
$("#gray").width(w_red+w_yellow);

根据您的更新

config.hourPerPercent=parseInt(data.totalspace)/100;
var futureNum=new Number((1/config.hourPerPercent)*parseInt(data.inuse));
var recNum=new Number((1/config.hourPerPercent)*parseInt(data.used));

config.Usage=futureNum.toFixed(2);              
config.Used=recNum.toFixed(2);
var factor=1.0;
if( (config.Usage + config.Used)>100 )
{
 factor=(config.Usage + config.Used)/100;
 config.Usage= Math.round(config.Usage / factor);
 config.Used=100-config.Usage;
}


$('#red').css('width',config.Used+'%');         
$('#yellow').css('width',config.Usage+'%');

这样会有+/-1的误差。但它要好得多。

关于javascript - 使用javascript计算宽度并调整css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783042/

相关文章:

javascript - 如何检查图像 slider 中哪个图像的不透明度为 1 以进行编号?

javascript - 如何防止浏览器绘制的 img 不可见?

javascript - 尝试制作轮播 slider

php - 如何处理dompdf两列设计?

Javascript + CSS 动画不工作,可能是什么原因造成的?

javascript - 无法使用 jQuery 添加 html 标签和关联数据

javascript - jQuery不同的div id显示/隐藏

javascript - 在没有 PHP 的情况下将 JS 数组传递到另一个页面

javascript - HTML/JS : Calculating and displaying price

javascript - Gulp - 管理库依赖项