PHP包含条件注释


php include with conditional comments

我在我的网站上包含了一些jQuery脚本。该脚本不工作与任何低于IE7。现在我想做以下操作:

<!--[if !(lt IE 7]>
    <?php include 'script.html'; ?>
<![endif]-->

它应该只在浏览器"不低于IE7"时加载脚本。但这行不通。

有没有办法解决这个没有使用基于PHP的浏览器识别?

是的,将浏览器识别构建到jQuery/javascript中。在javascript中,测试你需要的功能对象,如果它不存在,然后有代码来处理它。

可以是开头(没有结尾)?

帮助第一部分:它不起作用,因为您在lte之前不需要(,也不需要!。使用

<!--[if gte IE 7]>
  <?php include 'script.html'; ?>
<![endif]-->

进一步阅读:微软关于IE条件注释的页面

另一种选择是使用众所周知的ie7.js脚本,它使旧的IE版本更符合"标准",这肯定会使你的jQuery脚本工作。

你可以在这里找到

你不应该使用浏览器检测。相反,使用Feature Detection来测试你的浏览器是否能够做一些你想做的事情

在PHP中,您将执行以下操作之一

$browser = get_browser(null, true);
if($browser['browser'] == 'MSIE' && $browser['version'] >= 7) { /*CODE*/

$u_agent = $_SERVER['HTTP_USER_AGENT']; 
$bname = 'Unknown';
$version= "";
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
{ 
    $bname = 'Internet Explorer'; 
} 
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
    // we have no matching number just continue
}

IE条件语句只有在页面被发送到浏览器后才能工作,所以PHP包含文件将不起作用,要包含JS脚本文件,您可以使用

<!--[if !(lt IE 7]>
<script src='script.js' type='text/javascript'></script>
<![endif]-->

对于javascript浏览器检测,您可以使用:

if(BrowserDetect.browser == "MSIE" && BrowserDetect.version >= '7') {
   /* CODE */
}