如何在WordPress中实现评论区textarea自动调整高度
WordPress评论区textarea自动调整高度解决方案
一、问题根源
之前的JS/jQuery方案失效,基本是这两个原因:
- 脚本执行时机不对(DOM还没加载完成就运行了)
- 选择器没匹配到WordPress默认的评论textarea(默认ID是
comment)
二、原生JS解决方案(无依赖,推荐)
直接在主题的functions.php中添加以下代码,确保脚本在页面底部加载,DOM就绪后执行:
function auto_resize_comment_textarea() { ?> <script> document.addEventListener('DOMContentLoaded', function() { const textarea = document.getElementById('comment'); if (!textarea) return; // 初始化高度,适配已有内容 textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; // 监听输入事件,实时调整高度 ['input', 'keyup', 'change'].forEach(eventType => { textarea.addEventListener(eventType, function() { this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px'; }); }); }); </script> <?php } add_action('wp_footer', 'auto_resize_comment_textarea');
三、jQuery兼容方案(如果习惯用jQuery)
注意WordPress默认启用了jQuery.noConflict(),不能直接用$,要改用jQuery或者用自执行函数包裹:
function auto_resize_comment_textarea_jquery() { ?> <script> jQuery(document).ready(function($) { const $commentTextarea = $('#comment'); if (!$commentTextarea.length) return; // 初始化高度 $commentTextarea.css('height', 'auto').css('height', $commentTextarea[0].scrollHeight + 'px'); // 实时调整高度 $commentTextarea.on('input keyup change', function() { $(this).css('height', 'auto').css('height', this.scrollHeight + 'px'); }); }); </script> <?php } add_action('wp_footer', 'auto_resize_comment_textarea_jquery');
四、为什么<div contenteditable="true">不行?
WordPress评论表单只默认收集name为comment的textarea的值,div元素没有name属性,表单提交时不会把div里的内容传给后台,所以无法识别评论内容。
内容的提问来源于stack exchange,提问作者onlyoreoo
相关产品推荐
相关产品推荐

