有可能有一个按钮开始下载一个dom元素? [英] Is it possible to have a button start a download of a dom element?

查看:144
本文介绍了有可能有一个按钮开始下载一个dom元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在一个页面中生成的svg,我没有从外部来源中引入它。我想这个svg可以下载打印。有没有办法(使用客户端Javascript)下载一个dom节点作为文本文件?我仅限于这个项目的dojo和d3库。

I have an svg that is generated in a page, I am not bringing it in from an outside source. I want this svg to be downloadable for printing. Is there a way (using client side Javascript) to download a dom node as a text file? I am limited to dojo and d3 libraries for this project.

推荐答案

假设客户端正在使用HTML5网络浏览器,使用 < a> s 属性。您需要使用模拟点击 https://developer.mozilla.org/en-US/docs/DOM/document.createEventrel =nofollow noreferrer> MouseEvent ,如果您希望行为可以通过其他方法来调用,但不必将节点附加到文档。 我已经回答了类似的问题 ,但是在这里,设置< a> s href 到svg的文件位置,除非它是动态创建的 - 在这种情况下,您将对描述它的文本进行编码,以创建一个 数据URI

Assuming the client is using a HTML5 web browser, this can be achieved pretty easily using <a>s download attribute. You will need to simulate a click with a MouseEvent on this element if you want the behaviour to be invoked by some other means, but the node does not have to be appended to the document. I've answered a similar question about this before, but here, set the <a>s href to the svg's file location unless it is created dynamically ‒ in that case you would encode the text describing it to create a data URI.

可以从其 获得描述SVG的XML文本> SVGSVGElement 节点使用 XMLSerializer

XML text describing a SVG can be obtained from it's SVGSVGElement node using XMLSerializer.

var serializer = new XMLSerializer();
serializer.serializeToString(svg); // xml string for `svg` (your node)

请注意,任何另存为对话框将取决于客户端的配置。

Please note that any "Save As" dialogue will depend on the client's configuration.

// assuming var `svg` for your SVG node
var a = document.createElement('a'), xml, ev;
a.download = 'my_svg.svg'; // file name
xml = (new XMLSerializer()).serializeToString(svg); // convert node to xml string
a.href = 'data:application/octet-stream;base64,' + btoa(xml); // create data uri
// <a> constructed, simulate mouse click on it
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(ev);

这篇关于有可能有一个按钮开始下载一个dom元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆