javascript - d3 防止拖拽特定元素

标签 javascript svg d3.js

我正在尝试在 d3 中绘制几个矩形。我有一个数组,其中包含矩形属性的 JSON 对象。

var rectObj = {
    id : 'streams',
    x : 10,
    y : 10,
    height : 50,
    width : 100, 
    drag:'true'
};

一些矩形有 draggable='true',而其他矩形有 draggable='false'。

我想在单个 SVG 中绘制所有矩形。他们的做法是,

var rectangles = mainLayout
            .selectAll('rect')
            .data(rectObjects)
            .enter()
            .append('rect');

rectangles
        .attr("x", function (d) { return d.x; })
        .attr("initial-x", function (d) { return d.x; })
        .attr("y", function (d) { return d.y; })
        .attr("initial-y", function (d) { return d.y; })
        .attr("height", function (d) { return d.height; })
        .attr("width", function (d) { return d.width; })
        .attr("fill", function () { return "white"; })
        .attr("stroke", function () { return "black"; })
        .style("stroke-width", function() { return "1 px"; })
        .attr("draggable",function(d){return d.drag;})
        .call(dragStream)
;

在 dragStream 上,我想停止执行拖动功能。也就是说,那些矩形不应该在拖动时做任何事情。

var dragStream= d3.behavior.drag()
                    .on('dragstart', function(){
                        console.log('drg' + d3.select(this).attr('draggable'));
                        if(d3.select(this).attr('draggable') == 'false'){
                           // what should I do here ? 
                        }
                    })
            .on('drag', move /* this function is defined and works well*/)
            .on('dragend', function(){ // I do some stuff here

   });

我应该怎么做才能得到上面的要求?

最佳答案

您需要区分拖动事件,而不是 dragstart。

.on('drag', function(d, i) { if(d3.select(this).datum().drag) move.call(this, d, i); }).

如果你使用 .datum()。那么你不需要写任何属性。当 d3 将数据绑定(bind)到存储在 DOM 元素上的选择时,您可以使用 .datum() 访问它。此方法返回的值是对数据数组对象的引用,因此您可以在那里访问 drag 属性。

关于javascript - d3 防止拖拽特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30732091/

相关文章:

javascript - JS 破坏我的 Random 函数

javascript - 为 Outlook 生成 .msg 文件

javascript - SVG 中的可拖动和可调整大小

javascript - 可以将自定义图标添加到 font-awesome-react

javascript - 使用深度优先样式的 D3js 可折叠树进入过渡

javascript - Object.assign() 导致 TypeError : this. map is not a function

javascript - async.each 和 async.eachSeries 之间的区别

javascript - 如何响应地扩展 SVG?

javascript - 使用 D3.js 解析上传的 CSV 文件

d3.js - 如何删除d3中的第一个刻度