根据操作系统显示或隐藏Div

时间:2014-01-04 14:16:39

标签: javascript html operating-system detection os-detection

我经营一个网站,我希望能够为Windows播放可下载的程序。

摘要:

If Operating System = Windows

Then set visibility of Div 'adforwindows' to visible
Else Set visibility of Div 'adforwindows' to hidden

有没有人知道一个好的html / javascript脚本可以做到这一点?

修改

这是一个解决方案吗?似乎无法让它发挥作用;

<!DOCTYPE html>
<html>
<head>
<script>
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

if(OSName == "Windows"){
   document.getElementById('adforwindows').style.visibility = "visible";
}
else{
   document.getElementById('adforwindows').style.visibility = "hidden";
}
</script>
</head>
<body>
<div class="adforwindows">
Windows Advert 
</div>
<p>Main site content<P>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

因为你已经从这段代码中知道操作系统(取自网站)

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

因此,您可以使用简单的if语句来检查和记录.getElementById以设置可见性。

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

if(OSName == "Windows"){
   document.getElementById('adforwindows').style.display = "block";
}
else{
   document.getElementById('adforwindows').style.display = "none";
}

<小时/> 如果您不需要了解其他操作系统,只需使用此更短的代码:

if (navigator.appVersion.indexOf("Win")!=-1)
   document.getElementById('adforwindows').style.display = "block";
}
else{
   document.getElementById('adforwindows').style.display = "none";
}

<小时/> 编辑:如果您想要visibility:none/visible代替display:none(有区别:http://www.w3schools.com/css/css_display_visibility.asp 您可以将.style.display = "none";更改为.style.visibility = "hidden"; 并将.style.display = "block";更改为.style.visibility = "visible";

答案 1 :(得分:0)

您可以使用navigator.platformnavigator.appVersion

例如:

var getOS = function() {
    var operatingSystems = {
        'Win': 'Windows',
        'Mac': 'MacOS',
        'Linux': 'Linux',
        'X11': 'UNIX'
    };
    for(var k in operatingSystems) {
        if(navigator.appVersion.indexOf(k) !== -1) {
            return operatingSystems[k];
        }
    }
    return undefined;
};

console.log(getOS());

var os = getOS();
document.getElementById('adforwindows').style.display = os === 'Windows'
    ? 'block'
    : 'none';

DEMO

请参阅https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID