【问题标题】:Using visjs timeline, how to get start time (where I drop it) of a range item dropped in timeline使用 visjs 时间线,如何获取时间线中放置的范围项目的开始时间(我放置它的位置)
【发布时间】:2020-05-16 04:46:16
【问题描述】:

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);

});

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

【问题讨论】:

    标签: javascript timeline vis.js vis.js-timeline


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多