我有一个javascript,可以<div>在点击时保存as html 的内容,这在chrome上运行得很好,但在firefox上却没有.
请帮我写一个跨浏览器的解决方案.
这是我的代码:
$(window).load(function(){
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'invo.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'Invoice','text/html');
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
CONTENT GOES HERE
</div>
<a href="#" onclick="return false;" id="downloadLink">Download</a>Run Code Online (Sandbox Code Playgroud)
显然,简单地将时间链接添加到文档可以修复Firefox中的问题; 大概是Firefox不喜欢click不在"页面中"的元素:
$(window).load(function(){
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
var fileName = 'invo.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'Invoice','text/html');
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
CONTENT GOES HERE
</div>
<a href="#" onclick="return false;" id="downloadLink">Download</a>Run Code Online (Sandbox Code Playgroud)
顺便说一句,在这种情况下,您可以重新使用原始的"按钮"链接来保存下载和href,这将使您免于其他不必要的DOM更改:
$(window).load(function(){
function downloadInnerHtml(filename, elId, mimeType, link) {
var elHtml = document.getElementById(elId).innerHTML;
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
}
var fileName = 'invo.html';
$('#downloadLink').click(function(){
downloadInnerHtml(fileName, 'Invoice','text/html', this);
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
CONTENT GOES HERE
</div>
<a href="#" id="downloadLink">Download</a>Run Code Online (Sandbox Code Playgroud)