/**
* Registers settings and controls with the Customizer.
*
* @param WP_Customize_Manager $wp_customize Customizer object.
*/
function mytheme_customize_register( $wp_customize ) {
$wp_customize->add_setting(
\'primary_color\',
[
\'default\' => \'#b3000e\',
\'sanitize_callback\' => \'sanitize_hex_color\',
\'transport\' => \'postMessage\',
]
);
$wp_customize->add_control(
new WP_Customize_Color_Control(
$wp_customize,
\'primary_color\',
[
\'label\' => __( \'Primary Color\', \'mytheme\' ),
\'section\' => \'mytheme_color_options\',
]
)
);
}
add_action( \'customize_register\', \'mytheme_customize_register\' );
/**
* This will output the custom WordPress settings to the live theme\'s WP head.
*
* Used by hook: \'wp_head\'
*
* @see add_action(\'wp_head\',$func)
* @since MyTheme 1.0
*/
function mytheme_customizer_header_output() {
?>
<style type="text/css">
:root {
--primary: <?php echo esc_attr( get_theme_mod( \'primary_color\', \'#b3000e\' ) ); ?>;
}
</style>
<?php
}
add_action( \'wp_head\', \'mytheme_customizer_header_output\' );
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*/
function mytheme_customize_preview_js() {
wp_enqueue_script( \'mytheme-customizer-preview-script\', get_stylesheet_directory_uri() . \'/assets/js/customizer-preview.js\', [ \'jquery\', \'customize-preview\' ], 1.0, true );
}
add_action( \'customize_preview_init\', \'mytheme_customize_preview_js\' );
customizer-preview.js code
( function( $ ) {
wp.customize(
\'primary_color\',
function ( value ) {
value.bind(
function ( to ) {
//$( \'a\' ).css( \'color\', to );
$( \':root\' ).css( \'--primary\', to );
}
);
}
);
} )( jQuery );
最合适的回答,由SO网友:RiddleMeThis 整理而成
快速注释:
看起来您可能希望使用颜色控件,而不是排除type
以及获取默认文本控件。
例如,这会将文本输入转换为颜色选择器。。。
$wp_customize->add_control(
new WP_Customize_Color_Control(
$wp_customize,
\'primary_color\',
[
\'label\' => __( \'Primary Color\', \'mytheme\' ),
\'section\' => \'mytheme_color_options\',
\'type\' => \'color\'
]
)
);
你没有给出很多关于你的问题、你犯了什么错误或你试图实现什么的细节。或者为什么要使用自定义属性变量?
无论如何,我不认为可以使用jQuery以这种方式访问变量。试试这个。。。
( function( $ ) {
wp.customize(
\'primary_color\',
function ( value ) {
value.bind(
function ( to ) {
document.body.style.setProperty(\'--primary\', to);
}
);
}
);
} )( jQuery );
更新时间:
jQuery仅支持3.2.0及更高版本中的CSS自定义属性。2中不支持它们。x或更早,因此使用访问它们。css()在这些版本中不起作用。