doumei4964 2012-03-22 02:33
浏览 447
已采纳

在JS中更改div宽度的百分比

I have a very basic script that calculates and changes the width of a div but its not working it keeps giving a 100 % result .

My script is like this:

<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>

The PHP numbers are showing correct in the JS as:

var hp = 500;
var max = 2500;

Any ideas why it might not be working ?

  • 写回答

5条回答 默认 最新

  • douyanqu9722 2012-03-22 03:07
    关注

    You have to wait until the document (DOM) to load first.

    //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+"%");   
    });​
    

    DEMO: http://jsfiddle.net/DerekL/uUBVd/

    enter image description here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计