【问题标题】:How to use SVG with grunt and jade如何将 SVG 与 grunt 和 jam 一起使用
【发布时间】:2014-10-22 08:31:52
【问题描述】:

我在我的项目中使用 svg 文件,我喜欢将它们“内嵌”在 html 中,这样我就可以使用 css/js 来摆弄它们。

我对这种方法有 2 个问题:

  • 我使用的是jade模板引擎,所以我必须在添加之前将xml转换为jade
  • 添加很多xml代码真的把我的jade文件搞乱了

到目前为止,我加载 svg 图标的方式如下:我将它们放在 assets 文件夹中,然后像这样将它们加载到玉中:

          div
            img(src='/assets/svg/my_icon.svg')

但是在这里,我不能使用 js/css 来设置它们的样式。

有没有什么办法,例如使用 Grunt,在我的资产文件夹中查找,获取 xml 并用它填充我的 html 代码?

【问题讨论】:

  • 我不知道 Jade,但你能在 SVG 中包含 CSS/JS 吗?

标签: javascript html css svg gruntjs


【解决方案1】:

我的方法是在 Gruntfile.js 中使用 grunt-svgstore 和以下设置

svgstore: {
  default:{
    options: {
      prefix : 'icon-', // This will prefix each ID,
      svg: { // will add and overide the the default xmlns="http://www.w3.org/2000/svg" attribute to the resulting SVG
        viewBox : '0 0 100 100',
        xmlns: 'http://www.w3.org/2000/svg'
      }
    },
    files: {
      "<%= folders.src %>/jade/_svgDef.jade": ["<%= folders.src %>/svg/*.svg"]
    }
  }
}

注意:我将文件夹中的所有 SVG 直接编译到一个 jade 文件中,我将其包含在我的 layout.jade 中,如下所示:

.svgdef(style="display:none;")
  include _svgDef

对于任何 SVG,grunt-svgstore 都会创建漂亮的 ID 供您包含:

svg(viewBox="0 0 100 100", xmlns="http://www.w3.org/2000/svg")
    use(xlink:href="#icon-Twitter")

这很酷,因为现在您可以在 CSS 中设置此 SVG 样式,同时让您编辑的玉文件保持整洁!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2014-07-23
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多