JavaScript (mp3、mp4、jpg、doc、txt、rar)单个、多文件批量下载
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/muguli2008/article/details/79592465
JavaScript 多文件下载
HTML5中 a 标签多了一个属性——download,用户点击链接浏览器会打开并显示该链接的内容,若在链接中加了 download 属性,点击该链接不会打开这个文件,而是直接下载。
注意,是HTML5中的新特性,所以低版本浏览器不兼容!
1、单个文件下载: 以下载mp3为例:
重点在于:要在a标签中加上download属性;
<a download="xxx.mp3的文件名" href="http://www.xxx.com/upload/xxx.mp3">音乐下载</a>
2、多个文件批量下载:
同上面的单个文件下载原理一样,
不同点在于:
因为有多个文件,所以就要模拟次点击事件,根据要下载的数量来进行对应的循环生成a标签dom,并循环模拟点击下载事件。
其实现代码如下:
var btn = document.getElementById('#button');
//将要进行多文件下载的mp3文件地址,以组数的形式存起来(这里只例了3个地址)
var mp3arr = ["http://www.xxx.com/xxx.mp3", "http://www.xx.com/xxx.mp3", "http://wwww.xxx.com/xxx.mp3"];
function download(name, href) {
var a = document.createElement("a"), //创建a标签
e = document.createEvent("MouseEvents"); //创建鼠标事件对象
e.initEvent("click", false, false); //初始化事件对象
a.href = href; //设置下载地址
a.download = name; //设置下载文件名
a.dispatchEvent(e); //给指定的元素,执行事件click事件
}
//给多文件下载按钮添加点击事件
btn.onclick = function name(params) {
for (let index = 0; index < mp3arr.length; index++) {
download('第'+ index +'个文件', mp3arr[index]);
}
}
关于JS中的
自定义事件的定义和触发(createEvent, initEvent,dispatchEvent)
1、document.createEvent(eventType ) //创建新的 Event 对象。
参数:eventType 共5种类型:
Events :包括所有的事件.
HTMLEvents:包括 'abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize', 'scroll', 'select', 'submit', 'unload'. 事件
UIEevents :包括 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'keydown', 'keypress', 'keyup'.间接包含 MouseEvents.
MouseEvents:包括 'click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup'.
MutationEvents:包括 'DOMAttrModified', 'DOMNodeInserted', 'DOMNodeRemoved',
'DOMCharacterDataModified', 'DOMNodeInsertedIntoDocument',
'DOMNodeRemovedFromDocument', 'DOMSubtreeModified'.
2、event.initEvent(eventType) //初始化新事件对象的属性
在document.createEvent()后必须初始化,其对应的5种对应的初始化方法
HTMLEvents 和 通用 Events:
initEvent( 'type', bubbles, cancelable )
UIEvents :
initUIEvent( 'type', bubbles, cancelable, windowObject, detail )
MouseEvents:
initMouseEvent( 'type', bubbles, cancelable, windowObject, detail, screenX, screenY,
clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget )
MutationEvents :
initMutationEvent( 'type', bubbles, cancelable, relatedNode, prevValue, newValue,
attrName, attrChange )
3. dom.dispatchEvent(event) //给节点分派一个合成事件。
在初始化完成后就可以随时触发需要的事件了,前面的dom就要触发事件的元素,
需要注意的是在IE 5.5+版本上请用fireEvent方法,还是浏览兼容的考虑
4. 其他事件例子
1 立即触发鼠标被按下事件
var fireOnThis = document.getElementByIdx_x('someID');
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
fireOnThis.dispatchEvent(evObj);
2 考虑兼容性的一个鼠标移动事件
var fireOnThis = document.getElementByIdx_x('someID');
if( document.createEvent )
{
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'mousemove', true, false );
fireOnThis.dispatchEvent(evObj);
}
else if( document.createEventObject )
{
fireOnThis.fireEvent('onmousemove');