使用变量设置图像的宽度

时间:2015-07-12 00:38:12

标签: javascript html css image width

我正在创建一个排名条形图,其中包含相同条形图的五次迭代。我想用一个实际上是百分比的变量来改变每个柱的宽度。我可以通过将每个百分比作为每个图像的宽度来轻松完成。像....

<!DOCTYPE html>
<html>
    <body>
        <table width="100%" cellspacing="0" cellpadding="0" >
            <tbody>
                <tr>
                    <td width="20%" >5 stars</td>
                    <td width="80%" bgcolor="#e2e2e2">
                        <img src="http://qr8.us/images/review-bar.jpg" width=80% height="10" alt=""/>
                    </td>
                </tr>
                <tr>
                    <td >4 stars</td>
                    <td bgcolor="#e2e2e2">
                        <img src="http://qr8.us/images/review-bar.jpg" width=14% height="10" alt=""/>
                    </td>
                </tr>
                <tr>
                    <td >3 stars</td>
                    <td bgcolor="#e2e2e2">
                        <img src="http://qr8.us/images/review-bar.jpg" width=3% height="10" alt=""/>
                    </td>
                </tr>
                <tr>
                    <td >2 stars</td>
                    <td  bgcolor="#e2e2e2">
                        <img src="http://qr8.us/images/review-bar.jpg" width=2%  height="10" alt=""/>
                    </td>
                </tr>
                <tr>
                    <td >1 star</td>
                    <td bgcolor="#e2e2e2">
                        <img src="http://qr8.us/images/review-bar.jpg" width=1% height="10" alt=""/>
                    </td>
                </tr>
            </tbody>
        </table>
    </body>
</html>

但是,我希望将该宽度应用为我在其他地方计算的变量的百分比。变量看起来像......

var ttlrevsprcntfive = 80;
var ttlrevsprcntfour = 14;
var ttlrevsprcntthree = 3;
var ttlrevsprcnttwo = 2;
var ttlrevsprcntone = 1;

我已经尝试了一切来使变量在每个图像的width属性中起作用。极大的失败。

如何将每个变量的值分配给图像宽度?记住它是一个百分比。谢谢

2 个答案:

答案 0 :(得分:0)

您是如何尝试应用该值的?

你可以做到这一点,例如通过这样做:

YourImageObject.style.width = ttlrevsprcntfive +&#34;%&#34;;

您可以获取YourImageObject,例如by document.getElementsByTagName(&#34; img&#34;)[ imageIndex ]或者通过document.getElementById(&#39; imageId &#39;)或使用JQuery

答案 1 :(得分:0)

这可能就是你要找的东西。 工作小提琴here

fun(0, 1)
array([[4, 5],                                 
       [6, 7]]) 

fun(1, 1)
array([[2, 3],
       [6, 7],
       [10, 11]])

至于你的评论,我已经用你的html源代码做了一个例子。查看更新的小提琴here 这应该做的工作。如果您满意,请接受此解决方案作为正确的anwser,然后单击左侧的箭头到帖子。