用变量设置图像的宽度

Set width of an image with a variable

本文关键字:图像 变量 设置      更新时间:2023-09-26

我正在创建一个具有相同条形图像的五次迭代的排名条形图。我想用一个百分比变量来改变每个条的宽度。我可以很容易地做到这一点,把每个百分比作为每个图像的宽度。像…

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

我已经尝试了一切让变量在每个图像的宽度属性工作。大失败。

如何将每个变量的值赋给图像宽度?记住这是一个百分比。由于

这可能是您正在寻找的。在这里工作

'use-strict';
(function(){
    function resize() {
        var img = document.getElementsByTagName('img');
        for(var i=0;i<img.length;i++) {
           img[i].style.width = 20 + '%';
           img[i].style.height = 20 + '%'; 
    }
}
}());

关于你的评论,我用你的html源代码做了一个例子。在这里查看更新的小提琴这样就可以了。如果你满意,请接受这个解决方案作为正确的答案,并点击左边的箭头到帖子。

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

你可以这样做:

YourImageObject.style。

你可以得到YourImageObject例如document.getElementsByTagName("img")[imageIndex]或document.getElementById('imageId')或使用JQuery。