【问题标题】:Getting image width using javascript have problem?使用 javascript 获取图像宽度有问题吗?
【发布时间】:2011-05-08 09:55:38
【问题描述】:

这是我从网络获得的用于获取图像宽度的代码。 效果很好。

<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 变量 上面的代码。我没有在那里得到宽度值。有什么要做的吗 在那里获得价值?

请帮帮我………… 提前致谢

【问题讨论】:

  • 你需要它做什么?就像 RoToRa 说的那样,这是不可能的,所以也许我们可以帮助您找到解决您最初需求的方法。

标签: javascript image callback size width


【解决方案1】:

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

例如:

var imgTesting = new Image();

imgTesting.src => "${str_applicationPath}/common/images/reports/"+report+".png"

//第二次警报//

alert(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);

【讨论】:

  • -1 嗯,是的。图像加载异步,因此在设置 src 后很可能不直接知道宽度。
【解决方案2】:

这是不可能的。那时宽度是未知的。这首先是 onload 事件的重点。您必须在 imgTesting_onload 的“第二次警报”处执行您想要的代码。

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 2013-06-19
    • 2020-09-13
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2014-07-06
    相关资源
    最近更新 更多