HTML實現通過超連結下載檔案,還附帶一些js輔助函式
阿新 • • 發佈:2018-11-12
下載檔案函式
download (src, fileName) {
let $a = document.createElement('a');
$a.setAttribute('href', src);
$a.setAttribute('download', fileName);
let fileLink = document.createElement('span');
fileLink.setAttribute('style', 'cursor: pointer; -webkit-tap-highlight-color: transparent');
$a.appendChild (fileLink);
let body = document.getElementsByTagName('body')[0];
body.appendChild($a);
fileLink.click();
body.removeChild($a);
},
常用輔助類
addClass: function (elem, cls) {
if (!this.hasClass(elem, cls)) {
elem.className = elem.className === '' ? cls : elem.className + ' ' + cls;
}
},
removeClass : function (elem, cls) {
if (this.hasClass(elem, cls)) {
let newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' ';
while (newClass.indexOf(' ' + cls + ' ') >= 0) {
newClass = newClass.replace(' ' + cls + ' ', ' ');
}
elem.className = newClass.replace(/^\s+|\s+$/g, '');
}
},