js naturalWidth与naturalHeight属性是获得图片原始的尺寸,不会因外部width和height属性设置的改变而改变。
示例如下:
01 | <!DOCTYPE html> |
02 | < html > |
03 | < head > |
04 | < meta charset = "UTF-8" > |
05 | < title ></ title > |
06 | </ head > |
07 | < body > |
08 | < img id = "image" src = "2.png" style = "display:block;" width = "100" height = "100" /> |
09 | < script > |
10 | window.onload = function(){ |
11 | var image = document.getElementById("image"); |
12 | console.log("原始宽度:"+image.naturalWidth); |
13 | console.log("原始高度:"+image.naturalHeight); |
14 | console.log("宽:"+image.width); |
15 | console.log("高:"+image.height); |
16 | } |
17 | </ script > |
18 | </ body > |
19 | </ html > |
运行结果:
我们可以看到,这个原始宽高,不受设置的影响。
需要注意的是:
图片必须提前加载,否则,图片原始宽高均为0,如下图: