如何实现jQuery siblings替代效果?解决WP联系表单动画失效问题
解决WordPress Contact Form 7下联系表单动画失效问题
问题根源分析
原来的jQuery代码依赖input和.tm-form-animatedline是直接兄弟元素的结构,但Contact Form 7自动给表单控件套了一层wpcf7-form-control-wrap的span容器,甚至把.tm-form-animatedline放到了p标签里,导致.siblings()方法根本找不到目标元素——因为现在input的直接兄弟是包裹它的span,而不是动画线条。
修改后的jQuery代码
直接替换你原来的contactFormEffect方法即可:
/* Contact Form Effect */ contactFormEffect: function () { $('.tm-form-field').on('focus', 'input, textarea', function () { // 找到当前输入框所在的父级tm-form-field,再查找里面的动画线条 $(this).closest('.tm-form-field').find('.tm-form-animatedline').css('width', '100%'); }); $('.tm-form-field').on('focusout', 'input, textarea', function () { var $fieldContainer = $(this).closest('.tm-form-field'); var $animatedLine = $fieldContainer.find('.tm-form-animatedline'); $animatedLine.css('width', 0); var $this = $(this); if ($this.val().trim().length !== 0) { $animatedLine.css('width', '100%'); } }); }
代码细节说明
closest('.tm-form-field'):不管输入框被嵌套多少层(比如CF7的span容器),这个方法都会向上找到最近的.tm-form-field父容器,确保我们定位到了正确的表单字段区域。find('.tm-form-animatedline'):在找到的容器内部搜索动画线条元素,不管它是直接在容器里,还是被放在p标签里,都能精准命中。- 把容器和线条元素缓存到变量里,避免重复DOM查询,这是提升前端性能的小习惯。
效果验证
现在不管CF7怎么调整内部的span或p标签结构,只要.tm-form-animatedline还在.tm-form-field容器里,动画效果就能正常触发:
- 输入框聚焦时,线条展开到100%宽度
- 输入框失焦时,如果内容为空,线条收缩到0;如果有内容,线条保持100%宽度
内容的提问来源于stack exchange,提问作者Nayeem Hyder Riddhi
相关产品推荐
相关产品推荐

