1

我正在编写一个小部件 UI,用户可以在其中操作小部件和文本。所需的 UI 功能之一是从字形中的图标列表中选择一个图标,当我使用 twitter bootstrap 时,应该可以在 JavaScript 中选择 CSS 中的“icon-”类,然后在 DIV 中显示它们. 但是,我对 Web 开发还比较陌生,所以不确定如何循环遍历所有 CSS 类,选择所有“icon-”类。我可以看到如何使用选择器来搜索 HTML 正文,例如使用$.find("[class^='icon-']");但我不确定如何执行类似的操作来搜索 CSS 文件本身并提取 CSS 图标类列表。

感谢您的任何指示。

4

2 回答 2

2

如果您的浏览器实现了CSSStyleSheet 接口,这样的事情应该可以工作:

var icons = [];
var cssRules = document.styleSheets[0].cssRules; // your bootstrap.css
for (var i=0; i<cssRules.length; i++) {
  var selectorText = cssRules[i].selectorText;
  if (selectorText && selectorText.match(/^\.icon-[a-z_-]+$/)) {
    icons.push(selectorText);
  }
}

http://jsfiddle.net/V2wjX/

于 2013-05-24T11:07:40.220 回答
0

我能想到的最好方法是创建一个可能值的数组,然后遍历它们。在这里,我为你做的:(来自这个页面

var icons = ["glass","music","search","envelope","heart","star","star-empty","user","film","th-large","th","th-list","ok","remove","zoom-in","zoom-out","off","signal","cog","trash","home","file","time","road","download-alt","download","upload","inbox","play-circle","repeat","refresh","list-alt","lock","flag","headphones","volume-off","volume-down","volume-up","qrcode","barcode","tag","tags","book","bookmark","print","camera","font","bold","italic","text-height","text-width","align-left","align-center","align-right","align-justify","list","indent-left","indent-right","facetime-video","picture","pencil","map-marker","adjust","tint","edit","share","check","move","step-backward","fast-backward","backward","play","pause","stop","forward","fast-forward","step-forward","eject","chevron-left","chevron-right","plus-sign","minus-sign","remove-sign","ok-sign","question-sign","info-sign","screenshot","remove-circle","ok-circle","ban-circle","arrow-left","arrow-right","arrow-up","arrow-down","share-alt","resize-full","resize-small","plus","minus","asterisk","exclamation-sign","gift","leaf","fire","eye-open","eye-close","warning-sign","plane","calendar","random","comment","magnet","chevron-up","chevron-down","retweet","shopping-cart","folder-close","folder-open","resize-vertical","resize-horizontal","hdd","bullhorn","bell","certificate","thumbs-up","thumbs-down","hand-right","hand-left","hand-up","hand-down","circle-arrow-right","circle-arrow-left","circle-arrow-up","circle-arrow-down","globe","wrench","tasks","filter","briefcase","fullscreen"]

现在您可以遍历这个数组,并根据需要创建元素。

for (var i=0,l=icons.length; i<l; i++){
    var el = document.createElement('i');
    el.className = 'icon-'+icons[i];
    document.getElementById("iconContainer").appendChild(el);
}

JSFIDDLE


至于搜索 CSS,我可以建议你写一个这样的函数:

您可能会使用AJAX ( jqXHR )以某种方式将 CSS 文件的内容转换为字符串。

然后,编写一个非常基本的解析脚本,它接受 CSS 字符串作为参数。

function getIcons(cssStr){
    var matches = cssStr.match(/\.icon\-\w*.*\{/g), icons = [];
    for (var i=0,l=matches.length; i<l; i++) icons.push(matches[i].replace(/\.icon\-/g,'').replace(/\W/g,''));
    return icons;
}

这将为您提供之前显示的数组。

JSFIDDLE

于 2013-05-24T10:44:27.630 回答