Getting the browser cursor from “wait” to “auto” without the user moving the mouse

前端 未结 15 1926
自闭症患者
自闭症患者 2020-11-27 13:49

I use this jQuery code to set the mouse pointer to its busy state (hourglass) during an Ajax call...

$(\'body\').css(\'cursor\', \'wait\');

15条回答
  •  有刺的猬
    2020-11-27 14:10

    Working solution on CodeSandbox

    Some of the other solutions do not work in all circumstances. We can achieve the desired result with two css rules:

    body.busy, .busy * {
      cursor: wait !important;
    }
    
    .not-busy {
      cursor: auto;
    }
    

    The former indicates that we are busy and applies to all elements on the page, attempting to override other cursor styles. The latter applies only to the page body and is used simply to force a UI update; we want this rule to be as non-specific as possible and it doesn't need to apply to other page elements.

    We can then trigger and end the busy state as follows:

    function onBusyStart() {
        document.body.classList.add('busy');
        document.body.classList.remove('not-busy');
    }
    
    function onBusyEnd() {
        document.body.classList.remove('busy');
        document.body.classList.add('not-busy');
    }
    

    In summary, although we have to change the cursor style to update the cursor, directly modifying document.body.style.cursor or similar does not have the intended effect, on some engines such as Webkit, until the cursor is moved. Using classes to affect the change is more robust. However, in order to reliably force the UI to update (again, on some engines), we have to add another class. It seems removing classes is treated differently from adding them.

提交回复
热议问题