簡體   English   中英

僅在瀏覽器為Firefox時使用javascript隱藏html元素

[英]Hide an html element using javascript only if browser is firefox

如果瀏覽器僅是Firefox,如何使用javascript隱藏div?

檢查Firefox瀏覽器

//Javascript
var FIREFOX = /Firefox/i.test(navigator.userAgent);

if (FIREFOX) {
  document.getElementById("divId").style.display="none";
}


<!-- HTML-->
<div id="divId" />

只需檢查特定於FF的JavaScript屬性。 例如

var FF = (document.getBoxObjectFor != null || window.mozInnerScreenX != null);

if (FF) {
    document.getElementById("divId").style.display = 'none';
}

這稱為功能檢測 ,它比用戶代理檢測更可取 即使是jQuery $.browser API (如果要使用if ($.browser.mozilla) ,也會使用該API )建議避免用戶代理檢測。

“是瀏覽器Firefox”幾乎總是錯誤的問題。 當然,您可以開始在User-Agent字符串中進行粗加工,但是它常常會引起誤解,除非是非常不得已的方法,否則不值得使用。

這也是一個棘手的問題,因為有許多瀏覽器不是Firefox,但是基於相同的代碼,因此實際上是相同的。 是SeaMonkey Firefox嗎? 是Flock Firefox嗎? 是Fennec Firefox嗎? 是Iceweasel Firefox嗎? 是Firebird(或Phoenix!)Firefox嗎? 是Minefield Firefox嗎?

更好的方法是確切確定為什么要區別對待Firefox,並對此功能進行嗅探。 例如,如果您想規避Gecko中的錯誤,則可以嘗試觸發該錯誤並從腳本中檢測到錯誤的響應。

如果由於某種原因無法實現,則嗅探Gecko渲染器的一般方法是檢查是否存在僅適用於Mozilla的屬性。 例如:

if ('MozBinding' in document.body.style) {
    document.getElementById('hellononfirefoxers').style.display= 'none';
}

編輯:如果需要在body或目標div在文檔中之前在<head>進行測試,則可以執行以下操作:

<style type="text/css">
    html.firefox #somediv { display: none }
</style>
<script type="text/javascript">
    if ('MozBinding' in document.documentElement.style) {
        document.documentElement.className= 'firefox';
    }
</script>
 if(document.body.style.MozTransform!=undefined) //firefox only
function  detectBrowser(){
  ....
}

hDiv = .... //getElementById or etc..

if (detectBrowser() === "firefox"){
  hDiv.style.display = "none"
}

您可以嘗試Rafeal Lima的CSS Browser Selector腳本。 它將一些類添加到OS,瀏覽器,js支持等HTML元素中。然后,您可以將這些類用作其他CSS和/或JS的掛鈎。 腳本運行后,您可以編寫類似html.gecko div.hide-firefox的CSS(或jQuery)選擇器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM