移动Web中图片自适应的两种JavaScript解决方法

本文主要说的是Web中图片根据手机屏幕大小自适应居中显示,图片自适应两种常见情况解决方案。开始吧
在做配合手机客户端的Web wap页面时,发现文章对图片显示的需求有两种特别重要的情况,一是对于图集,这种文章只需要左右滑动浏览,最好的体验是让图片缩放显示在屏幕有效范围内,防止图片太大导致用户需要滑动手指移动图片来查看这种费力气的事情,用户体验大大降低。二是图文混排的文章,图片最大宽度不超过屏幕宽度,高度可以auto。这两种情况在项目中很常见。另外,有人说做个图片切割工具,把图片尺寸比例都设定为统一的大小,但即使这样,面对各种大小的移动设备屏幕,也是无法适用一个统一方案就能解决得了的。而且如果需求太多,那服务器上得存多少份不同尺寸的图片呢?显示不太符合实际。

下面是图集类型,需求方要求图片高宽都保持在手机可视视野范围,js代码列在下面:

<script type="text/javascript"> $(function(){ var imglist =document.getElementsByTagName("img"); //安卓4.0+等高版本不支持window.screen.width,安卓2.3.3系统支持 /* var _width = window.screen.width; var _height = window.screen.height - 20; var _width = document.body.clientWidth; var _height = document.body.clientHeight - 20; */ var _width, _height; doDraw(); window.onresize = function(){ doDraw(); } function doDraw(){ _width = window.innerWidth; _height = window.innerHeight - 20; for( var i = 0, len = imglist.length; i < len; i++){ DrawImage(imglist[i],_width,_height); } } function DrawImage(ImgD,_width,_height){ var image=new Image(); image.src=ImgD.src; image.onload = function(){ if(image.width>30 && image.height>30){ if(image.width/image.height>= _width/_height){ if(image.width>_width){ ImgD.width=_width; ImgD.height=(image.height*_width)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } }else{ if(image.height>_height){ ImgD.height=_height; ImgD.width=(image.width*_height)/image.height; }else{ ImgD.width=image.width; ImgD.height=image.height; } } } } } }) </script>

注意:测试中发现安卓4.0+的系统对window.screen.width属性支持的不好,很多情况在首次加载时返回的屏幕像素不正确。本人的安卓2.3.3系统测试通过,支持该属性。据说,这是安卓系统的bug,可以通过setTimeout设置延时时间来解决这个问题。不过,这个方法,本人怎么测试都行不通。所以干脆还是另寻高明吧。发现window.innerWidth可以担此重任,没有发现兼容问题,ok。

下面是,第二种情况,图文并茂的文章类型。这时候只对图片宽度和手机宽度适应有要求,对高度不做限制,相对容易些。
改造上面的javascript代码,如下:

<script type="text/javascript"> $(function(){ var imglist =document.getElementsByTagName("img"); //安卓4.0+等高版本不支持window.screen.width,安卓2.3.3系统支持 var _width; doDraw(); window.onresize = function(){ //捕捉屏幕窗口变化,始终保证图片根据屏幕宽度合理显示 doDraw(); } function doDraw(){ _width = window.innerWidth; for( var i = 0, len = imglist.length; i < len; i++){ DrawImage(imglist[i],_width); } } function DrawImage(ImgD,_width){ var image=new Image(); image.src=ImgD.src; image.onload = function(){ //限制,只对宽高都大于30的图片做显示处理 if(image.width>30 && image.height>30){ if(image.width>_width){ ImgD.width=_width; ImgD.height=(image.height*_width)/image.width; }else{ ImgD.width=image.width; ImgD.height=image.height; } } } } }) </script>

说明:代码中的resize函数,是捕捉屏幕窗口变化,始终保证图片根据屏幕宽度合理显示。当然了,前提是像我的项目一样,文章直接为富文本格式,图片的父级标签已经设定了text-align:center的居中属性。如果你的文章内容是直接调用第三方的,那么你可以在上面的javascript代码中添加相应的处理语句即可。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdffd.html