gpt4 book ai didi

php - JS中改变div宽度的百分比

转载 作者:行者123 更新时间:2023-12-02 19:46:34 25 4
gpt4 key购买 nike

我有一个非常基本的脚本,可以计算和更改 div 的宽度,但它不起作用,它一直给出 100% 的结果。

我的脚本是这样的:

<script>
var hp = <? echo $row['hp']; ?>;
var max = <? echo $row['maxhp']; ?>;
var perc = Math.round(hp/max * 100);
if(perc > 100) perc = 100;
else if(perc < 0 ) perc = 0;
d = document.getElementById('health');
d.style.width= perc+"%";
</script>

<div id="health" style="background-color:green;min-height:5px;"></div>

PHP 数字在 JS 中显示正确,如下所示:

var hp = 500;
var max = 2500;

有什么想法可能无法正常工作吗?

最佳答案

您必须等待文档(DOM)首先加载。

//head

$(function(){ //same as "onload" (jQuery)
var hp = 500,
max = 2500,
perc = Math.round(hp/max * 100);
if(perc > 100){
perc = 100;
}else if(perc < 0 ){
perc = 0;
}
//have to wait until DOM loaded, or else it return "not found"
d = document.getElementById('health');
d.style.width= perc+"%";
alert(perc+"%");
});​

演示:http://jsfiddle.net/DerekL/uUBVd/

enter image description here

关于php - JS中改变div宽度的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com