Invalid assignment left-hand side with ternary if

前端 未结 2 1545
傲寒
傲寒 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 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 );
    

提交回复
热议问题