使用javascript获取图像宽度有问题吗?

时间:2010-11-11 11:08:37

标签: javascript image callback size width

这是我从网上获得的代码以获得图像宽度。 它很棒。

<script type="text/javascript">
function CreateDelegate(contextObject, delegateMethod)
{   
        return function()
            {
                return delegateMethod.apply(contextObject, arguments);
            }
}


function imgTesting_onload()
{
    image_width=this.width;
    alert(image_width);//First Alert
}
</script>
var imgTesting = new Image();
imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = "${str_applicationPath}/common/images/reports/"+report+".png"
//Second Alert//

但我需要访问// Second Alert //中的image_width变量 上面的代码。我没有得到宽度值。我还有什么要做的 在那里获得价值?

请帮助我......... 在此先感谢

2 个答案:

答案 0 :(得分:2)

那是不可能的。此时宽度未知。这是onload事件的重点。你必须在imgTesting_onload中的“Second alert”执行你想要的代码。

答案 1 :(得分:-1)

您可以使用 imgTesting.width 来获取图片宽度。

例如:

  

var imgTesting = new Image();

     

imgTesting.src =&gt; “$ {str_applicationPath} /普通/图像/报告/” +报告+ “PNG”

     

//第二次警报//

     

警报(imgTesting.width);

下面给出的代码不是必需的

function CreateDelegate(contextObject, delegateMethod)
{   
        return function()
            {
                return delegateMethod.apply(contextObject, arguments);
            }
}
function imgTesting_onload()
{
    image_width=this.width;
    alert(image_width);//First Alert
}
imgTesting.onload =CreateDelegate(imgTesting, imgTesting_onload);