点击页面文字闪现效果

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style lang="css">
        * {
            margin: 0;
            padding: 0;
        }
        
        body {
            width: 100%;
            height: 100vh;
        }
        
        .text_popup {
            animation: textPopUp 1s;
            position: absolute;
            user-select: none;
            white-space: nowrap;
            z-index: 999;
        }
        
        @keyframes textPopUp {
            0%,
            100% {
                opacity: 0;
            }
            50% {
                opacity: .5;
            }
            100% {
                transform: translateY(-50px)
            }
        }
    </style>
</head>

<body>
    <script>
        var getRandomColor = function() {
            return '#' + (function(h) {
                return new Array(7 - h.length).join("0") + h
            })((Math.random() * 0x1000000 << 0).toString(16))
        }
        var showText = function(textArr) {
            if (!textArr || textArr.length == 0) {
                return;
            }
            var index = 0;
            document.documentElement.addEventListener('click', function(e) {
                var x = e.pageX;
                var y = e.pageY;
                var text = document.createElement('span');
                text.setAttribute('class', 'text_popup');
                this.appendChild(text);
                if (textArr[index]) {
                    text.innerHTML = textArr[index];
                } else {
                    index = 0;
                    text.innerHTML = textArr[index];
                }
                text.style.color = getRandomColor();
                text.addEventListener('animationend', function() {
                    text.parentNode.removeChild(text);
                }, false)
                if (x < text.clientWidth) {
                    text.style.left = x + 'px';
                } else if (text.clientWidth > (document.documentElement.clientWidth - x)) {
                    text.style.left = (x - text.clientWidth) + 'px';
                } else {
                    text.style.left = (x - text.clientWidth / 2) + 'px';
                }

                text.style.top = (y - text.clientHeight / 2) + 'px';
                index++;
            }, false)
        }
        showText(['敬业', '爱岗', '诚实', '守信'])
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/przlovecsdn/article/details/81508888