I currently have a website using D3 and I'd like the user to have the option to save the SVG as an SVG file. I'm using crowbar.js to do this, but it only works on chrome. Nothing happens of safari and IE gives an access denied on the click() method used in crowbar.js to download the file.

var e = document.createElement('script'); 

if (window.location.protocol === 'https:') { 
    e.setAttribute('src', 'https://raw.github.com/NYTimes/svg-crowbar/gh-pages/svg-crowbar.js'); 
} else { 
    e.setAttribute('src', 'http://nytimes.github.com/svg-crowbar/svg-crowbar.js'); 
}

e.setAttribute('class', 'svg-crowbar'); 
document.body.appendChild(e);

How do I download an SVG file based on the SVG element on my website in safari, IE and chrome?

推荐答案

有5个步骤.我经常使用这种方法输出内联svg.

  1. 获取要输出的内联svg元素.
  2. get svg source by XMLSerializer.
  3. 添加svg和xlink的名称空间.
  4. 采用组件方法构建svg的url数据方案.
  5. 将此url设置为某个"a"元素的href属性,然后右键单击此链接下载svg文件.

//get svg element.
var svg = document.getElementById("svg");

//get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);

//add name spaces.
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
    source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
    source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}

//add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;

//convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);

//set url value to a element's href attribute.
document.getElementById("link").href = url;
//you can download svg file by right click menu.

Jquery相关问答推荐

JQuery:$.get 不是函数

将日期时间从 javascript 传递给 c# (Controller)

Jquery如何通过数组中的属性查找对象

如何使用 jQuery 禁用粘贴(Ctrl+V)?

jQuery增量读取AJAX流?

调整浏览器大小时调整jqGrid的大小?

使用 Javascript|jQuery 删除特定的内联样式

将返回的 JSON 对象属性转换为(较低的第一个)camelCase

如何在 jquery 中更新(附加到)href?

Jquery 和 HTML FormData 返回未捕获的 TypeError:非法调用

如何将数组传递给 jQuery .data() 属性

如何使用 jQuery 停止默认链接点击行为

使用 jQuery 获取 div 的可见高度

数据表日期排序dd/mm/yyyy问题

如何将参数传递给 jQuery 中的事件处理程序?

如何在一个元素上拥有多个数据绑定属性?

jQuery DataTables:控制表格宽度

你如何记录jQuery中一个元素触发的所有事件?

检测页面是否已完成加载

在 jquery 中使用 AJAX Post 从强类型 MVC3 视图传递模型的正确方法