JavaScript | 学习笔记 [1] 点击切换背景实例

本贴最后更新于 1005 天前,其中的信息可能已经事过景迁

写在前面

最近在学习 JavaScript,说来惭愧,学习进度比较低下基础语法大概学了 30% 左右,也是工作之余来学习,然后最近按照学习进度,做了个小小的 Demo,做个记录方便下次查阅。

实现思路

id 为:app 的盒子嵌套五个小盒子,然后点击五个小盒子获取盒子的 background-color 然后改变 app 的背景颜色。

JavaScript 部分

//获取元素 app 
var app = document.getElementById('app');
//打印输出一下
console.log(app.style.backgroundColor);
//获取元素 box
var box = document.querySelectorAll('.box');
//处理过程
for (let i = 0; i < box.length; i++) {
	//for循环box盒子获取有多少个box。
            box[i].onclick = function () {
		//box的第i个被点击后应该干嘛
                var color = this.style.backgroundColor;
		//新建color变量等于 当前盒子的背景颜色
                console.log(color);
		//打印输出一下颜色
                app.style.backgroundColor = '' + color + '';
		//赋予id:app的背景颜色等于当前被点击的box的颜色
            }
        }

完整部分

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        padding: 0;
        margin: 0;
    }
    .box {
        width: 60px;
        height: 60px;
        font-size: 2em;
        font-family: Arial, Helvetica, sans-serif;
        line-height: 60px;
        text-align: center;
        color: #fff;
        box-shadow: 0px 1px 3px rgb(0, 0, 0, .13);
        background-color: #eee;
        border-radius: 12px;
        margin: 15px;
    }


    .flx {
        height: 300px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
    }
</style>

<body>
    <div style="background-color: #303F9F;" class="flx" id="app">
        <div style="background-color: #F26E50;" class="box">A</div>
        <div style=" background-color: #F29E6D;" class="box">B</div>
        <div style=" background-color: #f2d680;" class="box">C</div>
        <div style=" background-color: #50a18e;" class="box">D</div>
        <div style="background-color: #6dd9bf;" class="box">E</div>
    </div>


    <script>
        var app = document.getElementById('app');
        console.log(app.style.backgroundColor);
        var box = document.querySelectorAll('.box');
        for (let i = 0; i < box.length; i++) {
            box[i].onclick = function () {
                var color = this.style.backgroundColor;
                console.log(color);
                app.style.backgroundColor = '' + color + '';
            }
        }
    </script>
</body>

</html>

End

无限进步

  • JavaScript

    JavaScript 一种动态类型、弱类型、基于原型的直译式脚本语言,内置支持类型。它的解释器被称为 JavaScript 引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在 HTML 网页上使用,用来给 HTML 网页增加动态功能。

    710 引用 • 1173 回帖 • 171 关注
  • 笔记

    好记性不如烂笔头。

    304 引用 • 777 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...