New
Loading...
Hiện nay người làm web đã chú trọng hơn với người dùng mobile nên một website khi thiết kế phải hỗ trợ cả trình duyệt mobile. Thông thường là sử dụng giao diện Reponsive hoặc code Detect mobile, sau đây là  hướng dẫn cách sử dụng code Detect mobile đơn giản bằng JavaScript giúp bạn dễ dàng làm web hơn.


Bước 1: Tạo một file js đặt tên tùy ý và chép đoạn code sau vào:
var mobile = function(){

        return {

            detect:function(){

                var uagent = navigator.userAgent.toLowerCase();

                var list = this.mobiles;

                var ismobile = false;

                for(var d=0;d<list.length;d+=1){

                    if(uagent.indexOf(list[d])!=-1){

                        ismobile = true;

                    }

                }

                return ismobile;

            },

            mobiles:[

                "midp","240x320","blackberry","netfront","nokia","panasonic",

                "portalmmm","sharp","sie-","sonyericsson","symbian",

                "windows ce","benq","mda","mot-","opera mini",

                "philips","pocket pc","sagem","samsung","sda",

                "sgh-","vodafone","xda","palm","iphone",

                "ipod","android"

            ]

        };

    }();


    if(mobile.detect()){

        alert('You are using a mobile phone.');  

    }else{

        alert('You are using a desktop browser');

    }
Bước 2: Đặt file js vừa tạo vào trong thẻ <head>

Bước 3: Sửa lại hàm bạn muốn thực hiện nếu là trình duyệt là mobile:

alert('You are using a mobile phone.');


hoặc ngược lại:

alert('You are using a desktop browser');

Bạn có thể thay thế tùy ý ví dụ như khi trình duyệt mobile thì chuyển qua skin mobile hoặc cho xuất hiện 1 file css viết riêng cho trình duyệt mobile chẳng hạn.