原先的樣子
點擊之后
如果沒有輸入內容則還原
否則為最新輸入
實現代碼
test.html
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <div class="box"> <span>單擊文本框清空原有內容,離開文本框時若未填寫內容則設置為之前的內容:</span> <div class="content"> <input type="text" name="name" value="Lucas"/> </div> </div> <style> div.box{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;} div.box span{color:#999;font-style:italic;} div.content{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;} input[type='text']{width:200px;height:35px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;} </style> <script> $(function(){ var text; // 全局變量用於保存文本框的內容 $("input:text").focus(function() { text = $(this).val(); $(this).val(""); }); $("input:text").blur(function() { $(this).val()!="" || $(this).val(text); }); }) </script>