2

vijs 时间线文档:https ://visjs.github.io/vis-timeline/docs/timeline/

我正在使用这个例子: https ://visjs.github.io/vis-timeline/examples/timeline/other/drag_drop.html

我想在时间线上放置一个范围项目,并设置我放置它的开始时间和一小时后的结束时间。

我有结束时间,没问题。

我正在使用此代码

function handleDragStart(event) {
var dragSrcEl = event.target;
event.dataTransfer.effectAllowed = 'move';
var item = {
        id: new Date(),
        type: 'range',
        content: event.target.innerHTML.trim()
    };
item.start = new Date();
item.end = new Date(1000*60*60 + (new Date()).valueOf());
event.dataTransfer.setData("text", JSON.stringify(item));

}

如果你看到: item.start = new Date(); 我得到的是实际时间,而不是我丢弃物品的时间。

我看到我可以有时间使用:

timeline.on('drop', function (properties) {
console.log(properties.time);

});

但我不能在函数中使用它。

4

1 回答 1

1

起初这是一件苦苦挣扎的事情,但我设法解决了它。以下内容可能对未来的读者有所帮助:

vis-timeline使用的版本7.4.2

第 1 步:定义侦听器

记住:dragend听众对于创建项目的准确结束时间很重要

    $('.media_elm').each(function (index, item) {
        item.addEventListener('dragstart', handleDragStart.bind(this), false);
        item.addEventListener('dragend', handleDragEnd.bind(this), false); // ***
    });

第 2 步:创建 DragStart 函数

function handleDragStart(event) {
    // Get element from event
    let element = event.target;

    // Create item
    let item = {
        id: element.id, // You should define id on the drag element(important)
        content: 'Element',
        type: 'range'
        // IMPORTANT
        // No need to define start or end time here
        // As the accurate start time automatically gets created after dropping the element on the timeline
    }

    // Add item to timeline
    event.dataTransfer.setData("text", JSON.stringify(item));
}

第 3 步:创建 DragEndFunction

function handleDragEnd(e) {
    let element = e.target; // This is the same element as we used before
    
    // Get item data
    let itemData = prevTimeline.itemSet.items[element.id].data; // Here element id is the one which we used to create item

    // Set end time based on the start time and duration
    // This will add 5 seconds to the start time(the time where the item was dropped)
    // You can also define the duration on the drag element and then use it here
    itemData.end = moment(itemData.start).add('5', 's');

    // Update timeline data (auto refreshes)
    prevTimeline.itemsData.update(itemData);
}
于 2020-11-30T04:29:28.727 回答