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


<html>
<head>
<script type="text/javascript">
/* 判断设备是否为PC */
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>
<img alt="" src="https://192.168.1.116:9999/ffzx/news/20140205/015212022_1.jpg" />
<div>
<img alt="" src="https://192.168.1.116:9999/ffzx/news/20140208/1386835169183.jpg" />
</div>
</div>
<br>
</body>
</html>

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

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