2012-02-23 25 views
1

我想这样的事情添加到我的网页标题,以加载JS和CSS文件只如果没有一个iPhone/iPad的:增加一个条件脚本中的链接,JS和CSS文件在页面页眉

if(!(navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) 
{ 
    //Link to js file 
    //Link to css file 
} 

第一行工作正常,我已经通过粘贴脚本来测试它,但我不知道如何获取链接的文件......特别是因为我想让js和css链接开始WP模板标签<?php echo get_stylesheet_directory_uri(); ?>

非常感谢您的帮助!

+0

你可以检查导航服务器端(所以直接在PHP),并使用WP API添加JS和CSS文件。否则,您需要将目录URI作为JS变量传递到页面中,并有条件地重新使用它。 – hakre 2012-02-23 14:30:52

+0

不是答案,但是如果陈述实际上检查其“不是iPhone”或“是iPod”。 if(!(navigator.userAgent.match(/ iPhone/i)|| navigator.userAgent.match(/ iPod/i)))''可能是你想要的 – Josh 2012-02-23 14:32:31

+0

[将变量从PHP传递给JS] http://stackoverflow.com/questions/8775680/passing-variables-from-php-to-js) – hakre 2012-02-23 14:32:39

回答

1

这是更好地检查使用PHP的用户代理,因为它更容易然后添加合适的HTML标签加载正确的CSS和JS文件。

<?php if (!preg_match('/iPhone/', $_SERVER['HTTP_USER_AGENT']) && !preg_match('/iPod/', $_SERVER['HTTP_USER_AGENT'])): ?> 
    <link href="<?php echo get_stylesheet_directory_uri() ?>/style.css"> 
    <script src="<?php echo get_stylesheet_directory_uri() ?>/script.js" type="text/javascript"></script> 
<?php endif; ?> 

否则它仅仅使用JavaScript的会增加不必要的复杂性,并且需要你使用一个js加载器RequireJS http://requirejs.org/

1

类似的东西:

<?php if(!(navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) : ?> 
    <link href="<?php echo get_stylesheet_directory_uri() ?>/main.css" type="text/css" rel="stylesheet" > 
    <script src="<?php echo get_stylesheet_directory_uri() ?>/main.js" type="text/javascript"></script> 
<?php endif ?> 
+0

谢谢seferov,但是这打破了页面! – 2012-02-23 21:37:34

5
<?php 
    if (!preg_match("{iPhone|iPod}i",$_SERVER['HTTP_USER_AGENT'])) 
    { 
     echo '<script src="yourscript.js"></script>'; 
     echo '<link href="yourstyle.css" rel="stylesheet" type="text/css">'; 
    } 
?> 
+0

感谢Tomas。这增加了代码,但是'<?php echo get_stylesheet_directory_uri(); ?>'部分?例如js链接需要'<?php echo get_stylesheet_directory_uri(); ?>/yourscript.js' – 2012-02-23 21:31:48

相关问题