input元素根據(jù)輸入內(nèi)容自動(dòng)適應(yīng)寬度參考代碼
當(dāng)前位置:點(diǎn)晴教程→知識管理交流
→『 技術(shù)文檔交流 』
:input元素根據(jù)輸入內(nèi)容自動(dòng)適應(yīng)寬度參考代碼 參考代碼如下: <!DOCTYPE html> <html>
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <title>input寬度自適應(yīng)</title> <style> body { font-size: 16px; font-family: Arial, Helvetica, sans-serif; }
#my-input { width: 20px; padding: 0; font-size: 16px; font-family: Arial, Helvetica, sans-serif; } #my-span { position: absolute; left: 0; visibility: hidden; } </style> </head> <body> <!-- 思路:將文字內(nèi)容賦值給隱藏的span,然后將input的寬度設(shè)置為span的寬度 --> <span id="my-span"></span> <input type="text" id="my-input" oninput="changeWidth()"> <script> function changeWidth() { var mySpan = $("#my-span"); var myInput = $("#my-input"); mySpan.html(myInput.val()); //給span賦值 if (mySpan.width() > 20) { myInput.css('width', mySpan.width()); } } </script> </body> </html> 該文章在 2023/3/27 16:22:40 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |