DnD機能をJavaScriptからテストしたいと考えています.
EventTarget.dispatchEvent を利用して dragstart イベントをトリガーさせると、
DataTransfer オブジェクトが生成されず、event.dataTransfer が undefined になってしまい、
マウスによるDnDと同じ挙動になりません.
dataTransfer
https://developer.mozilla.org/ja/docs/DragDrop/DataTransfer
実装サンプル
{
const dragStartHandler = function(event) {
console.info('dragStartHandler triggered');
console.info(event);
event.dataTransfer.setData('text', 'はろー' + event.target.id);
};
const dragEndHandler = function(event) {
console.info('dragEndHandler triggered');
};
const dragOverHandler = function(event) {
console.info('dragOverHandler triggered');
event.preventDefault();
};
const dragEnterHandler = function(event) {
console.info('dragEnterHandler triggered');
event.preventDefault();
};
const dragLeaveHandler = function(event) {
console.info('dragLeaveHandler triggered');
event.preventDefault();
};
const dropHandler = function(event) {
console.info('dropHandler triggered');
let transferedStr = event.dataTransfer.getData('text');
console.info(transferedStr);
event.preventDefault();
};
document.getElementById('div1').addEventListener('dragstart', dragStartHandler, false);
document.getElementById('div1').addEventListener('dragend', dragEndHandler, false);
document.getElementById('div2').addEventListener('dragover', dragOverHandler, false);
document.getElementById('div2').addEventListener('dragenter', dragEnterHandler, false);
document.getElementById('div2').addEventListener('dragleave', dragLeaveHandler, false);
document.getElementById('div2').addEventListener('drop', dropHandler, false);
document.getElementById('dragstart_trigger').addEventListener('click', function(event) {
document.getElementById('div1').dispatchEvent(new Event('dragstart'));
}, false);
}
#div1 {
width: 100px;
height: 100px;
background-color: #EDF;
}
#div2 {
width: 100px;
height: 100px;
background-color: #FED;
}
<div id="wrapper">
<div id="div1" draggable="true">div1</div>
<div id="div2">div2</div>
</div>
<button id="dragstart_trigger">trigger dragstart</button>
改善策があれば教えていただきたいです.