没图的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行完成的功能是将获取的输入值(颜色信息)赋予背景颜色。
备注:<var>变量详解(JavaScript)
备注:<document>对象详解(HTML)
备注:<getElementById>方法详解(HTML)
备注:<bgColor>方法详解(HTML)
四、整体代码:
<!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>
欢迎大家评论交流!!(来自一名励志用“普通话”讲技术的菜狗子~)
来源:CSDN
作者:打团从来人不齐
链接:https://blog.csdn.net/weixin_38118997/article/details/103563481