首页 > 解决方案 > WordPress 在 Functions.php 中使用 JavaScript 将 CSS 文件排队

问题描述

我正在尝试仅在移动设备上加载 CSS 文件。

我做了一些研究,发现最好的方法是使用 JS,所以这是我找到的代码:

$( document ).ready(function() {      
var isMobile = window.matchMedia("only screen and (max-width: 760px)");

if (isMobile.matches) {
    //Add your script that should run on mobile here
}
});

现在如何将下面的代码放入该代码中?

wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/responsive.css'    );

另外我如何将它包含在 Functions.php 文件中。

我尝试了以下方法,但没有成功

?>
<script>
$( document ).ready(function() {      
var isMobile = window.matchMedia("only screen and (max-width: 760px)");

if (isMobile.matches) {

wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/responsive.css'    );
    
}
});
</script>
<?php

标签: javascriptwordpressphp-enqueuewp-enqueue-scripts

解决方案


结合 PHP 和 JavaScript 是不可能的。PHP 只在服务器上运行,而 JavaScript 只在客户端上运行(有一些例外)。

使用函数的最后一个参数wp_enqueue_style来设置函数创建的标签的media属性。MDN 对属性的描述如下:<link>wp_enqueue_stylemedia

您还可以在媒体属性中提供媒体类型或查询;只有当媒体条件为真时才会加载此资源。

此属性指定链接资源适用的媒体。它的值必须是媒体类型/媒体查询。这个属性主要在链接到外部样式表时很有用——它允许用户代理为它运行的设备选择最适合的样式表。

资源

这意味着您可以在media属性中进行媒体查询。如果该媒体查询匹配,则将加载样式表。

<?php
add_action( 'wp_enqueue_scripts', 'add_responsive_style' );
function add_responsive_style() {
  wp_enqueue_style( 
    'responsive', // Handle.
    get_template_directory_uri() . '/responsive.css', // Path to file.
    [], // Dependencies.
    false, // Version number.
    'screen and (max-width: 760px)' // <-- Media.
  );
}
?>

这将输出:

<link href="yourtheme/responsive.css" rel="stylesheet" media="screen and (max-width: 760px)">

推荐阅读