![](/img/trans.png)
[英]wordpress - registering, enqueuing, and adding javascript functions.php
[英]WordPress enqueuing a CSS file using JavaScript inside Functions.php
我正在嘗試僅在移動設備上加載 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
function 的最后一個參數來設置由wp_enqueue_style
function 創建的<link>
標記上的media
屬性。 MDN 對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.
);
}
?>
這將 output:
<link href="yourtheme/responsive.css" rel="stylesheet" media="screen and (max-width: 760px)">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.