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

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

代码:

<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); 绘制矩形并填充

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章