php、.net、html代码控制用户访问显示手机端和电脑端内容
最近投置广告,要根据用户的UA展示对应的内容,记录下几种语言的方法。
php:
function isMobile()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$mobile_agents = array ('Mobile', 'Android', 'iPhone', 'phone', 'pad', 'pod', 'iPod', 'ios', 'iOS', 'iPad', 'BlackBerry', 'IEMobile', 'MQQBrowser', 'JUC', 'Fennec', 'wOSBrowser', 'BrowserNG', 'WebOS', 'Symbian', 'Windows Phone');
$ismobile = false;
foreach ($mobile_agents as $device) {
if (stristr($user_agent, $device)) {
$ismobile = true;
break;
}
}
return $ismobile;
}
$ismobile = ismobile();
if($ismobile == false) {
echo "电脑端显示";
}
else {
echo "手机端显示";
}
.net:
string agent = HttpContext.Current.Request.UserAgent;
string strUrl = HttpContext.Current.Request.Url.AbsolutePath;
if (agent == "" || agent == null)
{
Console.WriteLine("读取不到设备信息,爬虫、curl等。");
}
else
{
if (strUrl.Contains("waplogin") || strUrl.Contains("Signin"))
{
Console.WriteLine("自定义地址包含某字符串不去显示");
}
else
{
string[] ua_words = { "Mobile", "Android", "iPhone", "phone", "pad", "pod", "iPod", "ios", "iOS", "iPad", "BlackBerry", "IEMobile", "MQQBrowser", "JUC", "Fennec", "wOSBrowser", "BrowserNG", "WebOS", "Symbian", "Windows Phone" };
foreach (string item in ua_words)
{
if (agent.Contains(item))
{
Console.WriteLine("显示手机端内容");
break;
}
}
Console.WriteLine("显示电脑端内容");
}
}
html:
可用js去判断UA,但我更倾向于用屏幕宽度去判断。
ie8不支持window.innerWidth,可用 $(window).width(); //需要引用jquery.js
<script type="text/javascript">
var windowWidth = window.innerWidth;
if(windowWidth > 1060){
document.write("电脑端显示");
}
else {
document.write("手机端显示");
}
</script>';
本文出自 俞凌龙博客,转载时请注明出处及相应链接。
本文永久链接: https://blog.jlwz.cn/234