是否使用选择性刷新添加或删除HTML类?

时间:2017-07-11 作者:dodov

我读过Selective Refresh 我理解这一点。它完全重写指定selector. 例如:

$wp_customize->get_setting( \'nav_type\' )->transport = \'postMessage\';
$wp_customize->selective_refresh->add_partial( \'nav_type\', array(
    \'selector\' => \'#container nav\',
    \'render_callback\' => \'change_body_class\',
) );
这将删除<nav> id为的元素内部container 并将其替换为change_body_class 作用不过,正如函数名称所示,我只想更改<body> 要素为什么?嗯,在我的CSS中,我有不同的导航布局,可以通过<body>

问题

我希望在更改元素B的类时,有选择地刷新元素a旁边的快捷方式图标。这可能吗?如果是,how do I do it?

1 个回复
SO网友:Weston Ruter

对这可以通过创建自定义选择性刷新来实现Partial 类型,并重写refresh 方法。

下面是相关的JavaScript,它应该在Customizer预览中排队,使用customize-selective-refresh 作为其脚本依赖项:

wp.customize.selectiveRefresh.partialConstructor.body_class = wp.customize.selectiveRefresh.Partial.extend({

    /**
     * Class name choices.
     *
     * This is populated in PHP via `wp_add_inline_script()`.
     *
     * @type {Array}
     */
    choices: [],

    /**
     * Refresh partial.
     *
     * Override refresh behavior to bypass partial refresh request in favor of direct DOM manipulation.
     *
     * @returns {jQuery.Promise} Resolved promise.
     */
    refresh: function() {
        var partial = this, setting, body, deferred, className;

        setting = wp.customize( partial.params.primarySetting );
        className = setting.get();
        body = $( document.body );
        body.removeClass( partial.choices.join( \' \' ) );
        body.addClass( className );

        // Do good diligence and return an expected value from the function.
        deferred = new $.Deferred();
        deferred.resolveWith( partial, _.map( partial.placements(), function() {
            return \'\';
        } ) );
        return deferred.promise();
    }
});
然后,在PHP中注册partial时,可以使用此自定义类型:

$wp_customize->selective_refresh->add_partial( \'nav_body_class\', array(
    \'selector\' => \'nav\',
    \'type\' => \'body_class\',
) );
下面是一个完整的插件,演示了该技术:https://gist.github.com/westonruter/731e3106177ce2b067290ddbe602ce05

结束

相关推荐