2015-09-22 70 views
0

我想知道是否可以通過XSLT進行以下操作。我對它很陌生。XSLT - CSS樣式表的所有元素屬性的組合

說我有一個具有各種可能屬性的元素。對於每個屬性組合,我想顯示speudo-content。

元件,具有不同的屬性:

<!ATTLIST foo 
    apple CDATA #IMPLIED 
    peach CDATA #IMPLIED 
    kiwi CDATA #IMPLIED 
    ... 
> 

期望中的CSS:

foo[apple]:before { 
    content: '@apple: ' attr(apple); 
} 
foo[peach]:before { 
    content: '@peach: ' attr(peach); 
} 
foo[kiwi]:before { 
    content: '@kiwi: ' attr(kiwi); 
} 
foo[apple][peach]:before { 
    content: '@apple: ' attr(apple) ' @peach: ' attr(peach); 
} 
foo[apple][kiwi]:before { 
    content: '@apple: ' attr(apple) ' @kiwi: ' attr(kiwi); 
} 
foo[peach][kiwi]:before { 
    content: '@apple: ' attr(peach) ' @kiwi: ' attr(kiwi); 
} 
foo[apple][peach][kiwi]:before { 
    content: '@apple: ' attr(apple) ' @peach: ' attr(peach) ' @kiwi: ' attr(kiwi); 
} 

並不重要,但每個組合應該只出現一次的順序。有一些元素具有五個以上的屬性,因此通過XSLT獲取CSS的所有組合將非常有幫助。不幸的是,在我的情況下,js不是一個選項,輸出是純CSS2。

我無法圍繞如何解決這個問題,任何幫助,不勝感激。

回答

1

對於這類問題,XSLT是一個不好的選擇。最好使用通用編程語言。組合可以用包含每個屬性的比特的比特字段來表示。然後你可以運行數字1到2^n-1來枚舉所有的組合。

這裏是一個JavaScript示例:

function generateCss(items) { 
 
    var n = items.length; 
 
    var m = 1 << n; // 2^n 
 
    
 
    document.write('<pre>'); 
 

 
    for (var i = 1; i < m; i++) { 
 
    var subset = items.filter(function(item, index) { 
 
     // (1 << index) is the bit representing the current item. 
 
     return i & (1 << index); 
 
    }); 
 

 
    var attrs = subset.map(function(item) { 
 
     return '[' + item + ']'; 
 
    }).join(''); 
 

 
    var content = subset.map(function(item, index) { 
 
     return "'" + (index == 0 ? '' : ' ') + '@' + item + 
 
      ": ' attr(" + item + ")"; 
 
    }).join(' '); 
 

 
    document.write(
 
     'foo' + attrs + ':before {\n' + 
 
     ' content: ' + content + ';\n' + 
 
     '}\n'); 
 
    } 
 

 
    document.write('</pre>'); 
 
} 
 

 
generateCss([ 'apple', 'peach', 'kiwi' ]);

+0

太謝謝你了!你是救星! – DTR9000