<!DOCTYPE html> <html> <head> <title>javascript</title> <meta type="viewport" content="width=device-width,initial-scale:1.0,user-scalable:no"/> </head> <body> <input type="button" class="buttons" id="js_button" value="载入图片"/> <div class="image_con js_imageCon" id="js_imageCon"></div> </body> <script type="text/javascript"> var button = document.getElementById("js_button"); button.onclick = function(){ var image = document.createElement("img"); image.onload = function(){ var w = this.width; var h = this.height; var p = w/h; if(image.readyState=="complete"||image.readyState=="loaded"||image.complete){ //条件1,2是判断ie6-ie10;条件3是判断除ie6-ie10外的浏览器。 if(p>1){ //p>1 此条件可以按需修改 this.style.width = "300px"; this.style.height = "auto"; //切记要加,(只为跨过ie给img默认添加width和height属性坑这里的width和height的值是图片实际的尺寸),如果不加ie中会按照图片实际height显示,图会变形 }else{ this.style.width = "auto"; //同上 this.style.height = "180px"; } //以下两行代码切记写到onload事件里边,避免谷歌中图片尺寸更改时过程的可见(由大变小,或由小变大)。 var imgCon = document.getElementById("js_imageCon"); imgCon.appendChild(image); } }; image.src = "images/image.jpg" } </script> </html>
时间: 2024-10-31 06:50:51