更改主题定制器实时预览中的css变量值

时间:2019-09-04 作者:Bharath

我正在尝试更改customizer中的CSS变量值,但无法使用“postMessage”进行实时预览。如果我使用“刷新”选项,它就会工作。

有人能看一下代码并给我指出正确的方向吗。谢谢

customizer.php code

/**
 * 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 );

1 个回复
SO网友:oppenheimer

尝试替换

$( \':root\' ).css( \'--primary\', to );
使用

$( \':root\' ).get(0).style.setProperty( \'--primary\', to );