[英]how do I run a script only for IE 8
我有一個js文件,並且僅在瀏覽器為IE 8時才想運行一些代碼。有什么辦法可以做到這一點?
現在我只有這個,但是它適用於所有瀏覽器:
if ($.browser.msie) {
//do stuff for IE 8
}
看到JavaScript中的瀏覽器檢測? 和http://modernizr.com
這是最簡短的答案:
if (navigator.userAgent.match(/MSIE 8/) !== null) {
// do something in IE8
}
瀏覽器特定的代碼幾乎從來都不是一個好主意。 但是,如果必須執行此操作,則可以將代碼放入條件注釋中。
http://www.positioniseverything.net/articles/cc-plus.html
<!--[if IE 8]>
<script type="text/javascript">
// this is only executed for IE 8
</script>
<![endif]-->
好的,我自己這樣解決了它:
if ($.browser.msie && $.browser.version == 8) {
//my stuff
}
如果頁面小於IE9,您可以在標題中進行調用以重定向頁面嗎? 我發現自己經常為使用IE6-10的客戶這樣做。
在文件頭中,我稱
<!--[if IE 7]> <link rel="()" type="()" href="(Your link here.)"><![endif]-->
您可能要考慮的另一個選項是墊片或polyfil。 互聯網上有許多內容可以幫助縮小現代網頁設計和舊版瀏覽器之間的差距。 一個示例是Modernizr 。
您可以使用條件注釋來做到這一點(通過https://stackoverflow.com/a/10965091/1878731 ):
<!--[if IE 8 ]> <html class="ie8"> <![endif]-->
if ($('html').is('.ie8')) {
...
}
或不弄亂html(通過http://en.wikipedia.org/wiki/Conditional_comment ):
<script>
/*@cc_on
@if (@_jscript_version == 5.8) { // IE8 detected
// do something
}
@*/
</script>
您可以執行以下操作:
if (navigator.userAgent.indexOf('MSIE 8.0') !== -1) {
// this clause will only execute on IE8
}
$ .browser已過時,因此您不能在新的jQuery版本中使用此對象屬性,因此要支持此功能,您必須使用jQuery migration插件。以下是鏈接。 https://github.com/jquery/jquery-migrate/#readme
您可以使用document.documentMode獲取IE的版本。
switch(document.documentMode)
{
case 8:
//do something with IE8
break;
case 9:
//do something with IE9
break;
case 10:
//do something with IE10
break;
case 11:
//do something with IE11
break;
default:
console.log('Other browsers...');
}
有關文檔,請參見此處
嘗試像這樣使用
<script type="text/javascript">
if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
document.write('<script src="somescript.js"><\/script>');
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.