![](/img/trans.png)
[英]How can I detect a Scrollbar presence ( using Javascript ) in HTML iFrame?
[英]How can I detect a html class with javascript?
我使用這三行代碼來檢測較少的Internet Explorer版本。
<!--[if lt IE 7]><html class="lt-ie8 lt-ie7 lesser-browser get-lost-ie-user please-leave-now"><![endif]-->
<!--[if IE 7]><html class="lt-ie8 ie7"> <![endif]-->
<!--[if !IE]><!--><html class="gtie7"><!--<![endif]-->
使用javascript,如何確定<html>
元素是否啟用了lt-ie8類?
使用JavaScript,您可以使用:
document.getElementsByTagName("html")[0].classList.contains("lt-ie8");
這給出了類別列表。 如果未實現classList
,則可以通過以下方式檢查它:
if (document.getElementsByTagName("html")[0].className.indexOf("lt-ie8") != -1)
// The browser...
或使用jQuery的$.hasClass()
如果有一個類集):
$("html").hasClass("lt-ie8");
因此,您可以通過以下方式使用它:
if ($("html").hasClass("lt-ie8"))
// Class is enabled.
else
// Class is not there.
我將使用document.body.parentNode
來獲取您的<html>
標記,因為不需要像其他方法一樣搜索DOM。 重新實現jQuery的hasClass
方法是檢查javascript類在舊版瀏覽器中是否具有類的最佳方法,因為當存在多個類或該類是另一個類的子字符串時,其他方法通常不起作用。
function hasClass(elem, klass) {
return (" " + elem.className + " ").indexOf(" " + klass + " ") > -1;
}
if (hasClass(document.body.parentNode, "lt-ie8")) {
// ...
}
如果您僅針對現代瀏覽器,那么使用classList
是最佳選擇。
if (document.body.parentNode.classList.contains("lt-ie8")) {
// ...
}
if (document.getElementsByClassName('lt-ie8').length > 0) {
// EDIT due to the important comment below
//console.log("you are using a crappy browser");
alert("you are using a crappy browser");
}
var isBrowserCrappy = document.getElementsByTagName('html')[0].className.indexOf('lt-ie8') !== -1;
嘗試:
if( document.getElementsByTagName("html")[0].className == 'gtie7' )
alert( 'html has class "gtie7"' );
既然您已經用jquery
標記了問題,請使用:
if ($(".lt-ie8").length > 0) {
. . . do stuff . . .
}
我在Firefox,IE7,IE9和Chrome中對其進行了測試。 。 。 在所有這些上都能正常工作。 。 。
編輯: $("html.lt-ie8").length
更有效。 。 。
注意:在HTML4和XHTML中, class
不是<html>
標記的有效屬性。 即使它看起來可行,您也可以考慮將其移至<body>
標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.