设置src属性后无需重新加载页面后如何获取图像宽度 [英] How i can get image width after set src attribute without reload page

查看:108
本文介绍了设置src属性后无需重新加载页面后如何获取图像宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,如果我将图像源传递给它,它应该修改$(#image")元素的src属性,当我单击不在表单内的按钮时,将调用此函数(这意味着该页面不会被重新加载)

I have a function that if i pass a source of image to it, it should modify the src attribute of $("#image") element, this function is called when i click a button which isn't inside a form (this means that page is not reloaded)

function modify_image(image_src){
   $("#image").attr("src", image_src);
}

他的 src 更改后,如何获得此图像的宽度?

how i can get the width of this image after his src changed ?

推荐答案

加载图像是异步的,因此您必须等到图像加载后才能获得宽度:

Loading an image is async, so you have to wait until it's loaded to get the width :

function modify_image(image_src){
   $("#image").on('load', function() {
       var width = this.width;
   })
   .attr("src", image_src)
   .each(function() {
        if (this.complete) $(this).trigger('load');
   });
}

总是在已附加事件处理程序之后更改源,对于必须的缓存图像,请检查this.complete属性,并自己触发onload事件.

Always change the source after the onload event handler has been attached, and for cached images you must check the this.complete property and trigger the onload event yourself.

这篇关于设置src属性后无需重新加载页面后如何获取图像宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆