目前有兩種方法:
一種是利用媒體查詢@media,查詢用戶的屏幕大小,根據用戶屏幕大小實現一套代碼兼容pc與移動端
主要運用的CSS框架有bootstrap。
其優點是:一套代碼實現PC與移動端,維護成本較低
其缺點是:用戶會下載多餘無用的代碼,當用戶網速較差時,頁面加載過慢影響用戶體驗
另一種方法是通過userAgent 查詢,根據用戶設備跳轉不同的網頁,代碼如下:
<html>
<meta charset="utf-8">
<title></title>
<script>
var userAgent = navigator.userAgent
if(userAgent.toLowerCase().indexOf('android')!==-1
||userAgent.toLowerCase().indexOf('iphone')!==-1
||userAgent.toLowerCase().indexOf('ipad')!==-1){
location.href="m/index.html";
}else{
location.href="pc/index.html";
}
</script>
</html>
其優缺點和第一種正好相反。
兩種方法各有所長,看需求選擇相對應的方法,適合自身的——纔是最好的方法。