没图的JS都是耍流氓!!!
一、实现效果:
二、原理分析:
为了实现上述功能,我们一共需要做两件事情:
- 使用HTML完成输入框和按钮工具的搭建;
- 使用JS完成按钮功能到背景颜色的关联;
三、模块拆解:
1.HTML 之 <input> :
请输入颜色编码: <input id = "in1" type="color">
<input> 元素的功能是创建一个输入接口,根据属性 <type> 的不同,会出现不同种类的形状。在本例子中参数为 color ,即出现了可供操作者自由选择的调色板。<id> 属性顾名思义,即当前元素的引用凭据,我们在获得 <input> 元素的输入结果时,需要使用 <id> 元素来提取出结果。
2.HTML 之 <button> :
<button type="button" onclick = javascript:ChangeBackgroundColor()>提交</button>
<button> 元素的功能是创建一个按钮工具,根据输入文本的不同,会在按钮工具上显示出不同的文本信息。在本例子中,文本信息为 “提交” 。<type> 属性规定了提交按钮的类型,一共有三种,分别为:submit,button,reset;由于个人水平有限,对这三个属性的具体细节区分并不了解,个人的代码习惯是一律 button 属性 + 文本命名。<onclick> 属性是该元素最为重要的属性之一,它指定了当按钮被点击后执行的后续操作,本文中的后续操作是调用了一个名为 ChangeBackgroundColor() 的JS函数。
备注:<button>元素详细讲解(HTML)
3.JavaScript 之 ChangeBackgroundColor():
function ChangeBackgroundColor(){
var favorite = document.getElementById("in1").value;
document.bgColor = favorite;
}
该函数的第2行完成的功能是获取 <id> 值为 in1 的元素的值,即我们在上文中提到的 <input> 属性的输入值。第3行完成的功能是将获取的输入值(颜色信息)赋予背景颜色。<function> 功能为JS语法中的函数定义功能,整体可以分为两种:命名函数和匿名函数。由于函数内容较多,下文链接讲解针对函数部分单独列出:
备注:<var>变量详解(JavaScript)
备注:<document>对象详解(HTML)
备注:<getElementById>方法详解(HTML)
备注:<bgColor>方法详解(HTML)
function功能详解:
系列1:<function>功能之 函数定义 (JavaScript)
系列2:<function>功能之 函数参数 (JavaScript)
系列3:<function>功能之 函数调用 (JavaScript)
系列4:<function>功能之 函数闭包 (JavaScript)
四、整体代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>BackgroundColorChange</title>
</head>
<body>
<!-- input 元素应用 -->
请输入颜色编码: <input id = "in1" type="color">
<!-- buttom 元素应用 -->
<button type="button" onclick = javascript:ChangeBackgroundColor()>提交</button>
</body>
<script>
function ChangeBackgroundColor(){
var favorite = document.getElementById("in1").value;
document.bgColor = favorite;
}
</script>
</html>