Invalid assignment left-hand side with ternary if

前端 未结 2 1519
傲寒
傲寒 2021-01-12 15:53

I want to create an stylesheet like this:

var sheet = document.createElement(\'style\'); sheet.type = \'text/css\';
sheet.innerHTML = data.style;


        
相关标签:
2条回答
  • 2021-01-12 15:58

    You can always do :

    sheet.styleSheet ? sheet.styleSheet.cssText = data.style 
                     : sheet.appendChild(document.createTextNode(data.style));
    

    FIDDLE

    0 讨论(0)
  • 2021-01-12 16:11

    Here's the solution which won't leave future maintainers wondering what on earth the code does:

    function setSheetContent( sheet, text ) {
        if(sheet.styleSheet)
            sheet.styleSheet.cssText = text;
        else
            sheet.innerHTML = text;
    }
    
    var sheet = document.createElement('style');
    sheet.type = 'text/css';
    setSheetContent( sheet, data.style );
    

    or wrap it up for even more convenience (if you never want to change the content of an existing sheet)

    function stylesheetWithContent( sheet, text ) {
        var sheet = document.createElement('style');
        sheet.type = 'text/css';
        if(sheet.styleSheet)
            sheet.styleSheet.cssText = text;
        else
            sheet.innerHTML = text;
        return sheet;
    }
    
    var sheet = stylesheetWithContent( data.style );
    
    0 讨论(0)
提交回复
热议问题