前端杂谈 · Web

JavaScript 实现鼠标点击特效

小编 · 5月25日 · 2019年

下面这段JavaScript代码脚本,可在用户使用鼠标左键,点击网页任意位置时,出现”富强”, “和谐”, “友善”, “敬业”, “文明”, “民主”, “自由”, “平等”, “公正”, “法制”, “爱国”, “诚信”。

JavaScript 实现鼠标点击特效
<!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>
    <script>
        var fnTextPopup = function (arr, options) {
            if (!arr || !arr.length) {
                return
            }
            var index = 0;
            document.documentElement.addEventListener("click", function (event) {
                var x = event.pageX,
                    y = event.pageY;
                var eleText = document.createElement("span");
                eleText.className = "text-popup";
                this.appendChild(eleText);
                if (arr[index]) {
                    eleText.innerHTML = arr[index]
                } else {
                    index = 0;
                    eleText.innerHTML = arr[0]
                }
                eleText.addEventListener("animationend", function () {
                    eleText.parentNode.removeChild(eleText)
                });
                eleText.style.left = (x - eleText.clientWidth / 2) + "px";
                eleText.style.top = (y - eleText.clientHeight) + "px";
                index++
            })
        };
        fnTextPopup(["富强", "和谐", "友善", "敬业", "文明", "民主", "自由", "平等", "公正", "法制", "爱国", "诚信"]);
    </script>
    <style>
        .text-popup {
            animation: textPopup 1s;
            color: red;
            font-weight: 700;
            user-select: none;
            white-space: nowrap;
            position: absolute;
            z-index: 99;
        }

        @keyframes textPopup {

            0%,
            100% {
                opacity: 0;
            }

            5% {
                opacity: 1;
            }

            100% {
                transform: translateY(-50px);
            }
        }
    </style>
</head>

<body>
    <div style="height: 1000px; background:#666;"></div>
</body>

</html>

如果想自定义显示词语,替换掉fnTextPopup(["富强", "和谐", "友善", "敬业", "文明", "民主", "自由", "平等", "公正", "法制", "爱国", "诚信"]); 里面的文本内容即可。

0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!