作者:霸气的饭桶丶_130 | 来源:互联网 | 2023-09-04 12:48
原标题:Javascript-显示隐藏表单文字
实现思路
运用 onfocus、onblur事件
onfocus- - -获取焦点(鼠标点击输入框,输入框里面有闪动的光标)
onblur- - -失去焦点(鼠标不选中输入框,输入框里面失去闪动的光标)
-
给输入框设置一个默认值
-
获取输入框对象,给其绑定事件:onfocus 和 onblur,
当获取焦点时(onfocus)- - -判断输入框的value值是否是默认值,如果是默认值初始值,将value改为空,默认初始值就没有了,可以输入自己的
当时去焦点时(onblur)- - -判断输入框的value值是否没有值,没有的话,给value赋值默认值,未输入内容移开后又会显示默认值了
-
还可以给获取焦点和失去焦点两种状态的文字颜色设置不同,让两种状态区分的更明显
示例1:
代码:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="token punctuation">">
<title>获取/失去焦点title&gwww.yii666.comt;
<style>
input {
color: #ccc;
outline: none;
}
style>
head>
<body>
<input type="text" value="手机文章来源地址51648.html">
<script>
var text = document.querySelector('input');
text.onfocus = function() {
if (this.value === '手机') {
this.value = '';
}
this.style.color = '#333';
}
text.onblur = function() {
if (this.value === '') {
this.value = '手机';
}
this.style.color = '#ccc';
}
script>
body>
html>
页面效果:
示例2
代码:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatibl文章来源站点https://www.yii666.com/e" content="IE=edge">
<meta name="viewport" content="token punctuation">">
<title>用户名 显示 隐藏title>
<style>
input {
font-size: 14px;
color: #999;
outline: none;
padding: 3px 0 3px 10px;
bord文章来源地址51648.htmler: 1px solid #cccwww.yii666.com;
}
style>
head>
<body>
<input type="text" value="邮箱/ID/手机号" class="userName">
<script>
var userName = document.querySelector('.userName');
userName.onfocus = function() {
if (this.value === '邮箱/ID/手机号') {
this.value = '';
this.style.borderColor = 'pink';
} else {
this.style.borderColor = 'pink';
this.style.color = '#999';
}
}
userName.onblur = function() {
if (this.value === '') {
this.value = '邮箱/ID/手机号';
this.style.borderColor = '#ccc';
this.style.color = '#999';
} else {
this.style.borderColor = '#ccc';
this.style.color = '#333';
}
}
script>
body>
html>
页面效果:
来源于:Javascript-显示隐藏表单文字