为可变 WooCommerce 产品的转换属性和术语按钮添加颜色选项

时间:2021-05-31 04:44:01

标签: jquery wordpress woocommerce product

将属性和术语的下拉列表转换为按钮后,我正在寻找有关添加颜色作为颜色术语选项的帮助。

当前设计: enter image description here

最终结果: enter image description here


如果术语名称为黄色,则该按钮的背景变为 #ffff00,其颜色为白色 (#fff)。如果名称为蓝色,则背景变为 #0000ff,文本变为白色 -- 依此类推。

我只需要帮助添加一个,剩下的我自己来做。


基于 How to convert select options (product attributes) to clickable divs in variable product page in WooCommerce? 答案代码,这是我的尝试:

add_action( 'wp_footer', 'convert_attribute_and_terms_into_buttons' );
function convert_attribute_and_terms_into_buttons() { ?>

    <script type="text/javascript">

    jQuery(function($){

    var clone = $( ".single-product div.product table.variations select" ).clone( true,true );

    $( ".single-product div.product table.variations select option" ).each( function() {

        $( this ).attr( 'data-parent-id', $( this ).parent().attr( 'id' ) );

        }
    );

    $( ".single-product div.product table.variations select option" ).unwrap().each( function() {

        if ( $ ( this ).val() == '' ) {

            $( this ).remove();

            return true;

        }

        var option = $( '<div class="custom_option" data-parent-id="'+$( this ).data( 'parent-id' )+'" data-value="'+$( this ).val()+'">'+$( this ).text()+'</div>' );

        $( this ).replaceWith( option );

        }
    );

    $( clone ).insertBefore( '.single-product div.product table.variations .reset_variations' ).hide();


    $( document ).on( 'click', '.custom_option', function() {

        var parentID = $( this ).data( 'parent-id' );

        $( '.custom_option[data-parent-id='+parentID+']' ).removeClass( 'on' );

        $( this ).addClass( 'on' );

        $( ".single-product div.product table.variations select#"+parentID ).val( $ ( this ).data( "value" ) ).trigger( "change" );

        }
    );

    $( ".single-product div.product table.variations select" ).each( function() {

        if ( $ ( this ).find( "option:selected" ).val() ) {

            var id = $( this ).attr( 'id' );

            $( '.custom_option[data-parent-id='+id+']' ).removeClass( 'on' );

            var value = $ ( this ).find( "option:selected" ).val();

            $( '.custom_option[data-parent-id='+id+'][data-value='+value+']' ).addClass( 'on' );

        }

    });
});

</script>

<style>
div.custom_option {

    display: inline-block;

    border: 1px solid #333;

    margin-right: 5px;

    padding: 0px 10px 0px 10px;

    cursor: pointer;
}
div.custom_option.on {

    background-color: gray;

    color: white;
}
</style>
    <?php
}

1 个答案:

答案 0 :(得分:0)

suggestion_active_text { text-align: center; height: 100%; display: flex; place-content: center; align-items: center; } 包含属性的值。因为不是每个值都一定是颜色,我们会在一个数组中搜索它,如果找到颜色名称,我们通过 CSS 将背景和文本颜色代码应用到元素。

所以你得到:

$( this ).val()