You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除vis.js Timeline双击触发的添加项事件?

解决vis.js Timeline双击自动添加项的问题

嘿,我懂你现在的困扰——想关掉Timeline双击时自动添加新项的功能,但之前设置doubleClickMode:false没生效对吧?这是因为在vis.js 4.x版本里,这个配置项其实不是用来控制双击添加行为的,真正的核心在于editable的配置逻辑。

我给你两种实用的解决方案,你可以根据自己的需求来选:

方案一:精准控制编辑权限(推荐)

如果你还需要保留其他编辑功能(比如拖拽调整项的时间、删除项),但只想禁用双击添加,那可以把editable设置为一个对象,明确开启或关闭对应的操作:

// Configuration for the Timeline
var options = {
  clickToUse: true,
  editable: {
    add: false,        // 直接禁用双击添加新项的功能
    updateTime: true,  // 保留拖拽调整时间的功能(按需开启)
    remove: true       // 保留删除项的功能(按需开启)
    // 其他你需要的编辑配置可以在这里补充
  }
};

这样设置后,双击Timeline就不会再触发添加项的操作,同时你需要的其他编辑功能依然能正常使用。

方案二:阻止双击事件的默认行为

如果你需要保留editable:true的全量配置,只是想单独屏蔽双击添加的默认动作,那可以在doubleClick事件监听里调用preventDefault():

timeline.on('doubleClick', function (properties) {
  console.log("Double click event fired");
  properties.preventDefault(); // 阻止默认的添加项逻辑执行
});

这种方法会保留双击事件的触发(你依然能在控制台看到日志),但不会执行默认的添加新项动作。

修改后的完整测试代码

这里给你整合好的完整代码,你可以直接复制测试:

<!DOCTYPE html> 
<html> 
<head> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width"> 
  <title>JS Bin</title> 
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.css" rel="stylesheet" type="text/css" /> 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis.min.js"></script> 
</head> 
<body> 
  <div id="visualization"></div> 
  <script type="text/javascript"> 
    // DOM element where the Timeline will be attached 
    var container = document.getElementById('visualization'); 

    // Create a DataSet (allows two way data-binding) 
    var items = new vis.DataSet([ 
      {id: 1, content: 'item 1', start: '2014-04-20'}, 
      {id: 2, content: 'item 2', start: '2014-04-14'}, 
      {id: 3, content: 'item 3', start: '2014-04-18'}, 
      {id: 4, content: 'item 4', start: '2014-04-16', end: '2014-04-19'}, 
      {id: 5, content: 'item 5', start: '2014-04-25'}, 
      {id: 6, content: 'item 6', start: '2014-04-27', type: 'point'} 
    ]); 

    // 这里用方案一的配置,也可以换成方案二的写法
    var options = {
      clickToUse: true,
      editable: {
        add: false,
        updateTime: true,
        remove: true
      }
    }; 

    // Create a Timeline 
    var timeline = new vis.Timeline(container, items, options); 

    timeline.on('click', function (properties) { 
      console.log("Click event fired"); 
    }); 

    timeline.on('doubleClick', function (properties) { 
      console.log("Double click event fired");
      // 如果用方案二,取消下面这行注释即可
      // properties.preventDefault();
    }); 
  </script> 
</body> 
</html>

选一个适合你场景的方案测试一下,应该就能解决问题啦!

内容的提问来源于stack exchange,提问作者Iker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:34:30