【发布时间】:2017-07-27 15:29:50
【问题描述】:
问题:我找到了下面的javascript来检测是否是IPhone等等:
<script language=javascript>
function isApple(userAgent){
var iPhone = userAgent.match(/iPhone/i) !== null;
var Apple = userAgent.match(/Apple/i) !== null;
var Mac = userAgent.match(/Mac/i) !== null;
var iPod = userAgent.match(/iPod/i) !== null;
var iOS = userAgent.match(/iOS/i) !== null;
return iPhone || Apple || Mac || iPod || iOS;
}
// Use like this...
if(isApple(navigator.userAgent)){
document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="/bootstrap/css/iphone.css">');
}
</script>
但是,它不能正常工作。看来它会影响桌面(非苹果)和具有 css 样式的安卓,应该只影响 iPhone。
不确定是否有更好的方法。任何帮助将不胜感激
*****我可以根据以下脚本检测用户正在使用的设备:
var deviceType = (navigator.userAgent.match(/iPad/i)) == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i)) == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";
alert(deviceType);
但是,当我执行以下操作时,如果它是 iPhone,css 不适用于 iPhone。图像仍然失真。
if(deviceType == 'iPad' || deviceType == 'iPhone'){
document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="/bootstrap/css/iphone.css">');
}
以下是我正在使用的 CSS:
@media screen and (-webkit-min-device-pixel-ratio: 0) and (max-width: 991px) and (min-width: 768px){
#homepage .carousel .item {
/*height: auto !important;*/
margin-top: 115px !important;
}
}
@media screen and (max-width: 991px) and (min-width: 768px) and (orientation:landscape){
#homepage .carousel .item {
/*height: auto !important;*/
margin-top: 20px;
}
}
@media (max-width:961px) and (min-width: 768px) and (orientation:landscape){
#homepage .carousel .carousel-caption {
top: -20px !important;
}
}
/* Portrait and Landscape iphone*/
@media only screen
and (max-device-width: 480px)
and (orientation:portrait) {
#homepage .carousel .item {margin-top: 71px; height: 150px !important;}
#homepage .carousel .item img { max-width: 100%; height: auto; display: block; }
}
@media only screen
and (max-device-width: 480px)
and (orientation:landscape) {
#homepage .carousel .item { height: 250px !important; }
#homepage .carousel .item img { max-width: 100%; height: auto; display: block; }
}
【问题讨论】:
-
language=javascript 应该是 language="javascript" 也不需要指定语言。只需使用
-
“不确定是否有更好的方法” - 这取决于您在这里尝试解决的实际问题。通常,您会使用媒体查询为具有不同格式的移动设备提供服务,主要是根据设备宽度来确定如何显示内容。我们不知道您是否有正当理由尝试根据用户代理以不同方式对待设备。 (但即使在这种情况下,我通常也宁愿不使用额外的样式表,而是在 html 或 body 元素上设置一个类,以便其他格式可以基于此而有所不同。)
-
@SagarV
language=javascript与language="javascript"一样有效。然而,它们都没有意义,因为正确的 mime 类型是application/javascript。但正如你所说,没有必要包括在内。 -
我将在运行 chrome 的 Windows 10 计算机上添加,
navigator.userAgent包含“Apple”一词,因此这种样式对我来说会失败。完整的字符串是:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
标签: javascript ios css iphone