[英]How to clear text field on focus of text field
我想在用戶點擊它時清除文本字段
<input name="name" type="text" id="input1" size="30" maxlength="1000" value="Enter Postcode or Area" onfocus=="this.value=''" />
除非你正在做一些你想要清除onclick的特定事情,否則我建議(正如其他人已經注意到的那樣)使用onfocus動作。 這樣,如果有人使用選項卡進行導航,也會清除默認文本。
您還可以使用onblur檢查它是否為空以將其恢復:
<input type="text" value="Default text" name="yourName" onfocus="if(this.value == 'Default text') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Default text'; }">
為此,您需要使用腳本語言,可能是javascript。 這是一個例子
<input type='text' value'Some text' onclick='javascript: this.value = ""' />
希望這可以幫助。
編輯:
為了滿足大衛在這里解釋的是第二個例子,以防你正在尋找
<script type='javascript'>
var clear = true;
function clear(obj)
{
if(clear)
{
obj.value = '';
clear = false;
}
}
</script>
<input type='text' value'Some text' onfocus='clear(this);' />
使用jQuery庫:
<input id="clearme" value="Click me quick!" />
$('#clearme').focus(function() {
$(this).val('');
});
或者你可以簡單地使用占位符屬性例如<input name="name" type="text" id="input1" size="30" maxlength="1000" placeholder="Enter Postcode or Area"/>
您可以使用<input ... onfocus="this.value='';"/>
。
這樣,該字段將在獲得焦點時被清除。 但是,如果您只想在用戶點擊它時清除它(例如,當字段通過鍵盤獲得焦點時),則使用onclick
而不是onfocus
。
但是,正如David Dorward在評論中指出的那樣,用戶可能無法預料到這種行為。 因此,請務必在特定字段(例如搜索字段)上設置此功能。
這就是我將它用於溫度轉換器/計算器的方式 - 當用戶輸入(鍵盤)時,文本輸入框使用指定的功能計算; 當用戶選擇其他文本輸入(只有兩個輸入)時,所選的文本輸入將清除。
HTML:
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" onfocus="this.value='';" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" onfocus="this.value='';"placeholder="Temperature (Fahrenheit)" />
</p>
JavaScript的:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}
試試這個,它對我有用
將其添加到輸入標記中
<code>
onfocus="this.value='';"</code>
例如,如果您的代碼是
<code>
<input type="text" value="Name" /></code>
像這樣使用它
<code><input onfocus="this.value='';" type="text" value="Name" /></code>
function Clear (x) {if (x.cleared) {} else {x.value = ""; x.cleared = true}}
onfocus = "Clear (this)"
將以下腳本添加到js文件中:
var input1 = document.getElementById("input1")
input1.onfocus = function() {
if(input1.value == "Enter Postcode or Area") {
input1.value = "";
}
};
input1.onblur = function() {
if(input1.value == "") {
input1.value = "Enter Postcode or Area";
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.