实现如下效果 , 默认状态下 , 表单显示灰色提示字体 , 点击表单输入内容是黑色字体的 ;
在 JavaScript 中 , 当 DOM 元素 获得焦点时 , 该 DOM 元素上绑定的 onfocus 事件被触发 ;
绑定 onfocus 事件的方法 :
// 行内设置 : 使用 onfocus 属性
<input type="text" onfocus="myFunction()">
// JavaScript 脚本中设置
var text = document.querySelector('input');
text.onfocus = function() {}
// 使用 addEventListener
document.getElementById("myInput").addEventListener("focus", function() {
// 执行相关操作
});
在 JavaScript 中 , 当 DOM 元素 失去焦点时 , 该 DOM 元素上绑定的 onblur 事件被触发 ;
绑定 onblur 事件的方法 :
// 行内设置 : 使用 onblur 属性
<input type="text" onblur ="myFunction()">
// JavaScript 脚本中设置
var text = document.querySelector('input');
text.onblur = function() {}
// 使用 addEventListener
document.getElementById("myInput").addEventListener("onblur", function() {
// 执行相关操作
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Style Operation Example</title>
<style>
input {
color: gray;
}
</style>
</head>
<body>
<input type="text" value="请输入搜索内容">
<script>
// 1. 使用 标签选择器 获取元素
var text = document.querySelector('input');
// 2. 注册 获得焦点 事件 onfocus
text.onfocus = function() {
// 如果 input 表单获取焦点 , 则显示 " 请输入搜索内容 " 内容
if (this.value === '请输入搜索内容') {
this.value = '';
}
// 获取焦点后 , 颜色变为黑色
this.style.color = 'black';
}
// 3. 注册 失去焦点事件 onblur
text.onblur = function() {
if (this.value === '') {
this.value = '请输入搜索内容';
}
// 失去焦点后 , 颜色变为灰色
this.style.color = 'gray';
}
</script>
</body>
</html>
默认状态时 , 显示如下样式 , input 表单中 显示 " 请输入搜索内容 " 字体是黑色的 ;
鼠标点击 表单 , 此时 灰色的字体 消失 , 表单中显示光标 ;
此时输入内容显示的是黑色字体 ;
完整的执行效果如下 :
实现如下开关灯效果 :
document.body.style.backgroundColor
属性 可 用于 设置 或 获取 HTML 页面 的背景颜色 ;
document.body.style.backgroundColor = "yellow";
var currentColor = document.body.style.backgroundColor;
console.log(currentColor); // 输出当前页面背景颜色
document.body.style.backgroundColor
显式设置值 , 则它将 返回空字符串或浏览器默认的背景颜色 ;代码示例 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Style Operation Example</title>
<style>
</style>
</head>
<body>
<button id="button">关灯</button>
<script>
var button = document.getElementById('button');
// 当前开灯状态 设置 1 , 背景白色 , 按钮显示 " 关灯 " , 点击按钮 切换到 关灯状态
// 当前关灯状态 设置 0 , 背景黑色 , 按钮显示 " 开灯 " , 点击按钮 切换到 开灯状态
var flag = 0;
button.onclick = function() {
if (flag == 0) {
document.body.style.backgroundColor = 'black';
button.innerText = '开灯';
flag = 1;
} else {
document.body.style.backgroundColor = 'white';
button.innerText = '关灯';
flag = 0;
}
}
</script>
</body>
</html>
执行效果 :