问题
I need to create a d3 brush which allows only for expansion/contraction on the right. i.e. I need to prevent the default behavior of move and expansion/contraction from the left.
From the docs, looks like this can be achieved by the filter
function(?) - but I am not seeing how to achieve the above use case. In this example, if I change the var brush
to
var brush = d3.brushX()
.extent([[0, 0], [width, height]])
.on("start brush", brushed)
.filter(function(){return event.button;})
;
to add the .filter
this is preventing the click on the right side as well :-)
回答1:
Your approach using .filter() will work if you check for the target of the mouse event. Your one-dimensional, horizontal brush will be constructed by D3 as follows:
<rect class="overlay" pointer-events="all" cursor="crosshair" x="0" y="0" width="960" height="500"></rect>
<rect class="selection" cursor="move" fill="#777" fill-opacity="0.3" stroke="#fff" shape-rendering="crispEdges" x="112" y="194" width="182" height="83"></rect>
<rect class="handle handle--e" cursor="ew-resize" x="289" y="189" width="10" height="93"></rect>
<rect class="handle handle--w" cursor="ew-resize" x="107" y="189" width="10" height="93"></rect>
Given this structure you need to filter out events targeted at <rect class="handle handle--w"/>
and <rect class="selection"/>
:
.filter(function() {
return !d3.event.button
&& !d3.select(d3.event.target).classed("handle--w")
&& !d3.select(d3.event.target).classed("selection");
})
This will filter out events targeted at the left handle (i.e. a <rect>
having class handle--w
) of the brush as well as those targeted at the selection itself. Have a look at the working demo.
Additionally, you have to adjust the styles for the cursor to not change its appearance when hovering the left brush handle and the selected area.
.handle--w, .selection {
cursor: auto;
}
来源:https://stackoverflow.com/questions/48493699/using-filter-on-a-horizontal-brush