无效的分配左侧与三元if

时间:2013-08-04 20:25:53

标签: javascript

我想创建一个这样的样式表:

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

it seems IE需要自己的语法。为了简化this answer代码,我尝试了

var sheet = document.createElement('style'); sheet.type = 'text/css';
(sheet.styleSheet ? sheet.styleSheet.cssText : sheet.innerHTML) = data.style;

但是抛出了ReferenceError: invalid assignment left-hand side

然后,我必须使用......

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

...还是有更简单的替代方案?

2 个答案:

答案 0 :(得分:3)

你总是可以这样做:

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

FIDDLE

答案 1 :(得分:1)

这里的解决方案不会让未来的维护者想知道代码究竟在做什么:

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 );

或将其打包以获得更多便利(如果您从不想更改现有工作表的内容)

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 );