HTML5自适应手机屏幕

时间:2021-05-12 17:10:58

从网上学到的自适应代码,用于HighCharts报表
使用js进行自适应控制,代码如下:

<script type="text/javascript">
var phoneWidth = parseInt(window.screen.width);
var phoneScale = phoneWidth/640;
var ua = navigator.userAgent;
if (/Android (\d+\.\d+)/.test(ua)){
var version = parseFloat(RegExp.$1);
if(version>2.3){
document.write('<meta name="viewport" content="width=640, minimum-scale = '+phoneScale+', maximum-scale = '+phoneScale+', target-densitydpi=device-dpi">');
}else{
document.write('<meta name="viewport" content="width=640, target-densitydpi=device-dpi">');
}
} else {
document.write('<meta name="viewport" content="width=640, user-scalable=no, target-densitydpi=device-dpi">');
}
</script>

完整html代码如下:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>ChartTestDemo</title>
<script src="./jquery/jquery.min.js"></script>
<script src="./highcharts/highcharts.js"></script>
<script src="./highcharts/modules/exporting.js"></script>
<script type="text/javascript">
var phoneWidth = parseInt(window.screen.width);
var phoneScale = phoneWidth/640;
var ua = navigator.userAgent;
if (/Android (\d+\.\d+)/.test(ua)){
var version = parseFloat(RegExp.$1);
if(version>2.3){
document.write('<meta name="viewport" content="width=640, minimum-scale = '+phoneScale+', maximum-scale = '+phoneScale+', target-densitydpi=device-dpi">');
}else{
document.write('<meta name="viewport" content="width=640, target-densitydpi=device-dpi">');
}
} else {
document.write('<meta name="viewport" content="width=640, user-scalable=no, target-densitydpi=device-dpi">');
}
</script>
</head>
<body>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(function() {
$('#container').highcharts({
chart: {
type: 'column'
},
title : {
text: '信息渠道人数'
},
subtitle : {
text: 'Source: WYM'
},
xAxis : {
categories: ['自营','互联网','户外','自然','自媒体','框架','400','其他'],
crosshair: true
},
yAxis : {
min: 0,
title: {
text: '人数(个)'
}
},
tooltip : {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y}人</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions : {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
credits : {
enabled: false
},

series: [{
name: '男',
data: [0, 7, 1, 2, 0, 3, 2, 1]
}, {
name: '女',
data: [3, 43, 14, 13, 9, 9, 3, 3]
}]
});
});
</script>
</body>
</html>

记录下来,以便以后使用