如何为动态添加的字段添加过渡或淡入效果
实现动态输入字段的CSS过渡效果
你现在的问题是直接添加/删除行时没有过渡效果,原CSS的transition没生效——这是因为动态添加的元素一开始就处于可见状态,没有属性变化的过程,transition自然起不了作用。可以纯CSS配合少量JS调整实现过渡,以下是解决方案:
原代码回顾
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="tbl_patient"> <thead> <tr> <th colspan="2" class="uk-text-center">Patient</th> </tr> </thead> <tbody> <tr> <td> <input type="text" id="patient" name="patient" placeholder="Patient Name"> </td> <td> <button type="button" name="add_patient" id="add_patient">+</button> </td> </tr> </tbody> </table>
CSS
td { transition: 0.5s ease 1s; }
JS
var i = 1; $('#add_patient').click(function() { i++; $('#tbl_patient').append('<tr id="row' + i + '" class="dynamic-added">\ <td>\ <input type="text" id="patient' + i + '" name="patient" placeholder="Patient Name" required>\ </td>\ <td>\ <button class="btn_remove" type="button" name="remove" id="' + i + '">--</button>\ </td>\ </tr>'); }); $(document).on('click', '.btn_remove', function() { var button_id = $(this).attr("id"); $('#row' + button_id + '').remove(); });
修改后的实现方案
核心思路
- 给动态添加的行设置初始隐藏状态(高度为0、透明度0、溢出隐藏)
- 用CSS
transition监听这些属性的变化 - 添加行后,延迟触发激活类让元素过渡到可见状态
- 删除行时,先触发淡出过渡,等动画结束再移除元素
修改后的完整代码
HTML(无需修改)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="tbl_patient"> <thead> <tr> <th colspan="2" class="uk-text-center">Patient</th> </tr> </thead> <tbody> <tr> <td> <input type="text" id="patient" name="patient" placeholder="Patient Name"> </td> <td> <button type="button" name="add_patient" id="add_patient">+</button> </td> </tr> </tbody> </table>
CSS
/* 动态行初始状态:隐藏 */ .dynamic-added { height: 0; opacity: 0; overflow: hidden; transition: all 0.5s ease; } /* 激活状态:正常显示 */ .dynamic-added.active { height: 40px; /* 根据你的输入框高度调整 */ opacity: 1; } /* 行内单元格的过渡(可选,优化细节) */ .dynamic-added td { padding: 0; transition: padding 0.5s ease; } .dynamic-added.active td { padding: 8px; }
JS
var i = 1; $('#add_patient').click(function() { i++; // 创建初始状态的行元素 const newRow = $(`<tr id="row${i}" class="dynamic-added"> <td> <input type="text" id="patient${i}" name="patient" placeholder="Patient Name" required> </td> <td> <button class="btn_remove" type="button" name="remove" id="${i}">--</button> </td> </tr>`); $('#tbl_patient').append(newRow); // 延迟添加激活类,确保DOM渲染完成后触发过渡 setTimeout(() => { newRow.addClass('active'); }, 10); }); $(document).on('click', '.btn_remove', function() { var button_id = $(this).attr("id"); const targetRow = $(`#row${button_id}`); // 移除激活类,触发淡出过渡 targetRow.removeClass('active'); // 等过渡完成后再删除元素(时间和transition时长一致) setTimeout(() => { targetRow.remove(); }, 500); });
说明
- 高度值要匹配你的输入框实际高度,避免内容被截断
- 过渡属性可按需调整,比如只保留透明度变化,或组合高度、padding的效果
- 10ms的延迟是为了让浏览器先渲染初始状态的元素,再触发属性变化,确保过渡生效
内容的提问来源于stack exchange,提问作者Pelin
相关产品推荐
相关产品推荐

