让我们浏览一下这个场景:
客户在结帐页面上,有一个复选框,其中包含文字:“这是礼物吗?”
如果选中该复选框,下面的字段将淡入以记笔记。
基于这个线程和其他一些线程,这里是我的代码:
add_filter( 'woocommerce_checkout_fields' , 'display_checkbox_and_new_checkout_field' );
function display_checkbox_and_new_checkout_field( $fields ) {
$fields['billing']['checkbox_trigger'] = array(
'type' => 'checkbox',
'label' => __('Checkbox label', 'woocommerce'),
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['new_billing_field'] = array(
'label' => __('New Billing Field Label', 'woocommerce'),
'placeholder' => _x('New Billing Field Placeholder', 'placeholder', 'woocommerce'),
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_new_field', 6 );
function conditionally_hide_show_new_field() {
?>
<script type="text/javascript">
jQuery('input#checkbox_trigger').change(function(){
if (this.checked) {
jQuery('#new_billing_field_field').fadeOut();
jQuery('#new_billing_field_field input').val('');
} else {
jQuery('#new_billing_field_field').fadeIn();
}
});
</script>
<?php
}
问题是当选中该框时应该淡入的字段已经可见。
如何更改脚本以使其在加载时不可见?
请尝试以下方法:
add_action( 'woocommerce_before_checkout_form', 'conditionally_show_hide_checkout_field' );
function conditionally_show_hide_checkout_field() {
?>
<style>
p#new_billing_field_field.on { display:none !important; }
</style>
<script type="text/javascript">
jQuery(function($){
var a = 'input#checkbox_trigger', b = '#new_billing_field_field'
$(a).change(function(){
if ( $(this).prop('checked') === true && $(b).hasClass('on') ) {
$(b).show(function(){
$(b).css({'display':'none'}).removeClass('on').show();
});
}
else if ( $(this).prop('checked') !== true && ! $(b).hasClass('on') ) {
$(b).fadeOut(function(){
$(b).addClass('on')
});
$(b+' input').val('');
}
});
});
</script>
<?php
}
add_filter( 'woocommerce_checkout_fields', 'add_custom_checkout_fields' );
function add_custom_checkout_fields( $fields ) {
$fields['billing']['checkbox_trigger'] = array(
'type' => 'checkbox',
'label' => __('Checkbox label', 'woocommerce'),
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['new_billing_field'] = array(
'label' => __('New Billing Field Label', 'woocommerce'),
'placeholder' => _x('New Billing Field Placeholder', 'placeholder', 'woocommerce'),
'class' => array('form-row-wide on'),
'clear' => true
);
return $fields;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)