JS 七彩文字

背景:

作者身为一个经历过杀马特时代的90后,怎么能拒绝七彩梦幻灯光呢, 手撸一个七彩文字控制器

 

效果:(文字颜色是会不停变化的)

代码:

 

<!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>Document</title>
</head>

<body>
    <style>
        #box {
            width: 500px;
            height: 200px;
            font-size: 50px;
            border: 1px solid;
        }
    </style>
    <div id="box"></div>
    <input type="text">
    <button>发送</button>

    <script>
        var oBox = document.querySelector('#box');
        var oIpt = document.getElementsByTagName('input')[0]
        var oBtn = document.querySelector('button');

        oBtn.onclick = function () {
            // setInterval 循环事件
            setInterval(rainbowStyle, 100);
        }

        var rainbowStyle = function () {
            var str = oIpt.value;
            var newStr = '';
            // 彩虹七色
            var arrColor = ['#FF0000', "#FF7F00", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#8B00FF"];
            for (var i = 0; i < str.length; i++) {
                var num = Math.round(Math.random() * 6);

                // 色彩域 rgb(255,255,255)
                // var num1 = Math.round(Math.random() * 255);
                // var num2 = Math.round(Math.random() * 255);
                // var num3 = Math.round(Math.random() * 255);
                // var color_val = 'rgb(' + JSON.stringify(num1) + ',' + JSON.stringify(num2) + ',' + JSON.stringify(num3) + ')'
                // newStr += '<span style="color:' + color_val + '">' + str.charAt(i) + "</span>";
                newStr += '<span style="color:' + arrColor[num % arrColor.length] + '">' + str.charAt(i) + "</span>";
            }
            oBox.innerHTML = newStr;
            return
        }
    </script>
</body>

</html>

 

博客园JS代码:

<script>
// 彩虹标题
var header_title = document.querySelector("#Header1_HeaderTitle");
var header_title_obj = document.getElementById("Header1_HeaderTitle")

var rainbowStyle = function () {
    var str = header_title_obj.textContent;
    var newStr = '';
    // 彩虹七色
    var arrColor = ['#FF0000', "#FF7F00", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#8B00FF"];
    for (var i = 0; i < str.length; i++) {
        var num = Math.round(Math.random() * 6);
        newStr += '<span style="color:' + arrColor[num % arrColor.length] + '">' + str.charAt(i) + "</span>";
    }
    header_title.innerHTML = newStr;
    return
}
!function () {
    // setInterval 循环事件
    setInterval(rainbowStyle, 100);
}()
</script>

 

posted @ 2023-01-04 15:36  萤huo虫  阅读(149)  评论(0编辑  收藏  举报