When using jQuery to determine whether it is mobile access, you can judge by detecting the width of the window or the user agent string.
The following are two methods:
Method 1: Detect Window Width
Example
$(document).ready(function() {
// Get the window width
var windowWidth = $(window).width();
// Set a threshold, e.g., 768px, adjust according to actual needs
var mobileThreshold = 768;
// Determine whether it is a mobile device
if (windowWidth < mobileThreshold) {
// Code executed on mobile
console.log("Mobile access");
} else {
// Code executed on non-mobile
console.log("Non-mobile access");
}
});
// Get the window width
var windowWidth = $(window).width();
// Set a threshold, e.g., 768px, adjust according to actual needs
var mobileThreshold = 768;
// Determine whether it is a mobile device
if (windowWidth < mobileThreshold) {
// Code executed on mobile
console.log("Mobile access");
} else {
// Code executed on non-mobile
console.log("Non-mobile access");
}
});
Try it »
Method 2: Detect User Agent String
Example
$(document).ready(function() {
// Get the user agent string
var userAgent = navigator.userAgent;
// Determine whether it contains mobile device keywords, e.g., "Android", "iPhone", "iPad", etc.
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
// Code executed on mobile
console.log("Mobile access");
} else {
// Code executed on non-mobile
console.log("Non-mobile access");
}
});
// Get the user agent string
var userAgent = navigator.userAgent;
// Determine whether it contains mobile device keywords, e.g., "Android", "iPhone", "iPad", etc.
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
// Code executed on mobile
console.log("Mobile access");
} else {
// Code executed on non-mobile
console.log("Non-mobile access");
}
});
Try it »
Which method to choose depends on your specific needs and project requirements.
Please note that detecting the user agent string is not 100% reliable, because the user agent string can be modified. Therefore, choose the appropriate method based on the specific situation.