基于两个文本框与parseInt()实现div自定义宽高的方案需求
双文本框实现Div自定义宽高(使用parseInt())
直接上落地代码,核心是用parseInt()把文本框的字符串输入转为整数,确保CSS能正确识别尺寸数值:
HTML 结构
<label for="txtWidth">宽度:</label> <input type="text" id="txtWidth" placeholder="输入宽度数值..." /> <br> <label for="txtHeight">高度:</label> <input type="text" id="txtHeight" placeholder="输入高度数值..." /> <br> <button id="btnSetSize">设置尺寸</button> <br> <div id="divResult" style="border:1px solid #ccc; padding:10px; margin-top:10px;"> 示例文本 </div> <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
JavaScript 逻辑
$(document).ready(function() { $('#btnSetSize').on('click', function() { // 转成十进制整数,第二个参数10避免八进制解析问题 const widthValue = parseInt($('#txtWidth').val(), 10); const heightValue = parseInt($('#txtHeight').val(), 10); // 处理非数字输入,给默认值兜底 const finalWidth = isNaN(widthValue) ? 200 : widthValue; const finalHeight = isNaN(heightValue) ? 100 : heightValue; // 批量设置宽高样式 $('#divResult').css({ 'width': finalWidth + 'px', 'height': finalHeight + 'px' }); }); });
关键细节
parseInt(val, 10)必须加第二个参数10,不然输入以0开头的内容会被误解析为八进制数- 用
isNaN()做有效性判断,防止用户输入非数字导致样式失效 - 用对象形式一次性设置
width和height,比多次调用css()更简洁
内容的提问来源于stack exchange,提问作者Bouke
相关产品推荐
相关产品推荐

