How do I remove :hover?

前端 未结 9 786
南方客
南方客 2020-12-15 03:41

I have a small problem with a script.
I want to have a default action on :hover for clients with Javascript disabled, but for those with Javascript enabled

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 04:46

    You could strip all :hover style rules from document.styleSheets.

    Just go through all CSS styles with JavaScript and remove all rules, which contain ":hover" in their selector. I use this method when I need to remove :hover styles from bootstrap 2.

    _.each(document.styleSheets, function (sheet) { 
        var rulesToLoose = []; 
        _.each(sheet.cssRules, function (rule, index) { 
            if (rule.selectorText && rule.selectorText.indexOf(':hover') > 0) { 
                rulesToLoose.push(index);
            }
        });
    
        _.each(rulesToLoose.reverse(), function (index) {
            if (sheet.deleteRule) {
                sheet.deleteRule(index);
            } else if (sheet.removeRule) {
                sheet.removeRule(index);
            }
        });
    });
    

    I did use underscore for iterating arrays, but one could write those with pure js loop as well:

    for (var i = 0; i < document.styleSheets.length; i++) {}
    

提交回复
热议问题