JavaScript实例1-页面特效-改变背景色

作者 : 开心源码 本文共1833个字,预计阅读时间需要5分钟 发布时间: 2022-05-13 共228人阅读

功能一:修改文档的背景颜色

代码:

<body><form>    <p align="left">请输入颜色编码:</p>    <input type="text"name="text" size="20" /> &nbsp;&nbsp;    <input type="button" name="button" value="修改颜色" onClick="change(this.form)" /></form><script language="JavaScript">        function change(form)        {            /*未输入颜色编码,弹出提醒框*/            if (form.text.value == "")                alert("你喜欢的颜色是?");            else            {                /*按输入颜色编码,修改背景颜色*/                document.bgColor=(""+form.text.value+" ");            }        }    </script></body>

运行结果

相关知识点

document颜色相关的属性如下:
bgColor:背景色
fgColor:前景色(文字颜色)
linkColor/alinkColor/vlinkColor: 链接色
可利用for(var x in document) { console.log(x)}命令在控制台查询document的一律属性

功能二:修改某个自己设置标签的背景颜色

代码:

<!-- 使用方法一 -->    <input id="input1" type="text">    <input id='button1' type="button" value="Button1">    <div id="box1" style="width: 100px; height: 100px; background-color: black;"></div>    <!-- 使用方法二 -->    <input id="input2" type="text">    <input id='button2' type="button" value="Button2">    <br>    <canvas id="box2" width="100" height="100" style="background-color: black;"></canvas>    <script>        // 方法一        const input1 = document.querySelector('#input1');        const button1 = document.querySelector('#button1');        const box1 = document.querySelector('#box1');        button1.onclick = function() {            if(input1.value === '') {                alert('请输入你喜欢的颜色!');            } else {                box1.style.backgroundColor = input1.value;            }        }        // 方法二        const input2 = document.querySelector('#input2');        const button2 = document.querySelector('#button2');        const box2 = document.querySelector('#box2');        button2.onclick = function() {            if(input2.value === '') {                alert('请输入你喜欢的颜色!');            } else {                const ctx = box2.getContext('2d');                ctx.fillStyle = input2.value;                ctx.fillRect(0,0,100,100);            }        }    </script>

运行结果

知识点

box1.style.backgroundColor = input1.value;获取HTML节点后,利用节点的style属性里面的backgroundColor属性修改backgroundColor的值,便修改了box1的背景色。
可以使用Object.getPrototypeOf(box1)查看box1包含的属性。

const ctx = box2.getContext('2d'); 获取HTML节点的2d环境对象
ctx.fillStyle = input2.value; 填充样式,canvas 的fillStyle可以填充纯色,渐变和模式
ctx.fillRect(0,0,100,100); 绘制矩形并填充

更多实例,可访问: 956159241/JSExamples
假如文章能够对您有所帮助,我便感到十分荣幸。如若文章能被您点赞,那便是万分荣幸~

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » JavaScript实例1-页面特效-改变背景色

发表回复