javascript - 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
解决方案
结合 PHP 和 JavaScript 是不可能的。PHP 只在服务器上运行,而 JavaScript 只在客户端上运行(有一些例外)。
使用函数的最后一个参数wp_enqueue_style
来设置函数创建的标签的media
属性。MDN 对属性的描述如下:<link>
wp_enqueue_style
media
您还可以在媒体属性中提供媒体类型或查询;只有当媒体条件为真时才会加载此资源。
和
此属性指定链接资源适用的媒体。它的值必须是媒体类型/媒体查询。这个属性主要在链接到外部样式表时很有用——它允许用户代理为它运行的设备选择最适合的样式表。
这意味着您可以在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)">
推荐阅读
- c# - 如何将 slug 添加到 asp.net 核心网站中的所有链接生成?
- ansible - 使用 ansible Ad-Hoc 命令在 /home/ubuntu/ 位置的“主机”机器文件夹 1 中创建一个文件夹
- regex - python:去除各种引号
- python - Python正则表达式模式匹配数字和单词问题?
- java - 如何在 Java 编程(CodeHS)中找到金字塔的表面积?
- javascript - Discord bot 的无垃圾邮件功能不起作用
- javascript - 使用 jquery ajax 需要来自 API 的响应才能进入表格 HTML
- jupyter - 向 Jupyter Hub/Lab 实例添加横幅消息?
- php - mysqli _connect 类的对象无法在第 135 行转换为字符串
- python - 多个索引答案 Python 3