首页 > 解决方案 > 经典 Asp - JavaScript:chrome 中的高度和宽度始终为零

问题描述

我的标记中有一个图像字段。我正在使用 javascript 设置其来源。我需要它的高度和宽度。为此,我使用了 image.height() 和 image.width() 方法。它在 Internet Explorer 中正常工作,但在 chrome 中不起作用,我尝试了 image.height 和 image.width 方法,但没有得到任何价值。我也尝试通过将 prop 方法更改为 attr 来设置图像 src,但它也给了我相同的结果。我在这里粘贴我的代码。

function new()
{
timg = new Image();
    timg.src=fpath; 
}

我用另一种方法称之为

function Size(timg) {

        var con=150;
        th=timg.height;
    alert("th="+th); //in chrome always returns Zero
        tw=timg.width;
    alert("tw="+tw); //in chrome always returns Zero
        }

请指教!

标签: javascripthtmlcssasp-classic

解决方案


你试试:

<script>
var tw = document.getElementById('YourElemId').clientWidth;
document.getElementById('result').innerHTML = tw;
</script>

<div id="result"></div>

浏览器兼容性。https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth

如果图像 id="YourElemId" 不成功,也许您可​​以使用 div id="YourElemId" 包装图像并执行 document.getElementById('YourElemId').clientWidth 。用于测试 div style="border:1px solid #000;max-width:?px;"

我读到 clientWidth 属性不适用于具有 display:inline? 的元素,默认情况下有几个元素内联,如 span、img 等。您可以尝试使用 style="display:block;" 设置元素 id="YourElemId"


推荐阅读