js判断设备是否为PC并调整图片大小

时间:2021-05-26

复制代码 代码如下:
<html>
<head>
<script type="text/javascript">

function isPC() {
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS","Windows Phone", "iPad", "iPod");
var flag = true;
for ( var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}


function AutoResizeImage(maxWidth, maxHeight, objImg) {
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
} else if (maxWidth == 0) { //
if (hRatio < 1) Ratio = hRatio;
} else if (maxHeight == 0) {
if (wRatio < 1) Ratio = wRatio;
} else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
}
if (Ratio < 1) {
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}


function setImg(tagid,pcWidth,pcHeight,appWidth,appHeight){
var tag=document.getElementById(tagid);
var images=tag.getElementsByTagName("img");
for(var i=0;i<images.length;i++){
if(isPC){
AutoResizeImage(pcWidth, pcHeight, images[i]);
}else{
AutoResizeImage(appWidth, appHeight, images[i]);
}
}
}
window.onload=function(){
setImg('imgDIV',300,0,300,0);
}
</script>
</head>
<body>
<div id="imgDIV">
<img alt="" src="http://192.168.1.116:9999/ffzx/news/20140205/015212022_1.jpg" />
<div>
<img alt="" src="http://192.168.1.116:9999/ffzx/news/20140208/1386835169183.jpg" />
</div>
</div>
<br>
</body>
</html>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章