首页 > 解决方案 > 为什么此 JS 代码中的光标不更新?

问题描述

我正在编写 javascript 代码,我得出的结论是,在 CPU 密集型代码之前执行时,更改 html 页面的任何/所有元素上的光标不会立即受到影响。即使移动我的鼠标,代码运行时也没有任何变化。

例如,此代码仅在 for 循环完成后更改光标:

$('*').css('cursor', 'wait'); for (let i=0; i<10000000000; i++) ;

如果我运行以下命令,用户甚至不会在循环期间看到任何变化:

$('*').css('cursor', 'wait'); for (let i=0; i<10000000000; i++) ; $('*').css('cursor', '');

任何其他 css 更改(背景颜色、元素大小等)都可以正常工作,但光标不能...

无论如何要解决这个问题?

(在 Chrome 和 Firefox 上测试过)

标签: javascriptcss

解决方案


我们可以:

<!DOCTYPE html>
    <html>

    <head>
        <title></title>
        <style>
            html {
                height: 100%;
            }

            body {
                height: 100%;
            }
        </style>
    </head>

    <body>
        <script>
            document.body.style.cursor = 'wait'
            getData()

            function getData() {
                for (let index = 0; index < 20; index++) {
                    console.log(index)
                }
                endWork()
            }
            function endWork() {
                setTimeout(() => {
                    document.body.style.cursor = 'default'
                    alert('change cursor to default')
                }, 3000);
            }
        </script>
    </body>

    </html>


推荐阅读