将d3滑块对象移动到特定位置

时间:2017-06-13 17:59:50

标签: javascript d3.js svg

我有滑块的代码:

var slider = d3.select('body').append('p').text('Title: ');

slider.append('label')
    .attr('for', 'threshold')
    .text('');
slider.append('input')
    .attr('type', 'range')
    .attr('min', d3.min(graph.links, function(d) {return d.value; }))
    .attr('max', d3.max(graph.links, function(d) {return d.value; }))
    .attr('value', d3.min(graph.links, function(d) {return d.value; }))
    .attr('id', 'threshold')
    .style('width', '50%')
    .style('display', 'block')
    .on('input', function () {
        var threshold = this.value;

        d3.select('label').text(threshold);

        var newData = [];
        graph.links.forEach( function (d) {
            if (d.value >= threshold) {newData.push(d); };
        });

  color.domain([d3.min(newData, function(d) {return d.value; }), d3.max(newData, function(d) {return d.value; })]).interpolator(d3.interpolateBlues);

        link = link.data(newData, function(d){ return d.value});
        link.exit().remove();
        var linkEnter = link.enter().append("path")
                      .style("stroke", function(d) { return color(d.value); })
                      .style("fill", "none")
                      .style("stroke-width", "3px");
        link = linkEnter.merge(link).style("stroke", function(d) { return color(d.value); });

        node = node.data(graph.nodes);

        simulation.nodes(graph.nodes)
    .on('tick', tick)
        simulation.force("link")
    .links(newData);

        simulation.alphaTarget(0.1).restart();

我会在哪里放置.attr("transform", "translate(10,10)")来定位滑块?我似乎无处不在。示例(https://bl.ocks.org/mbostock/6452972)首先使用svg.append(" g")进行分组,但我无法将其与当前代码集成。

1 个答案:

答案 0 :(得分:2)

您的滑块不是svg的一部分,它包含附加到主体的非svg元素。这些变换适用于svg元素,而不适用于非svg html元素。您需要像使用css一样更新元素的位置。

您要引用的示例通过使用svg元素来模拟滑块来创建svg滑块。滑块包含在svg g元素中,因此可以使用.attr("transform","translate(x,y)")移动

您可以使用css将滑块移动到任何其他html / non-svg元素。我在下面创建了一个示例,用于设置滑块的初始位置,然后在滑动时更新它(使用selection.style()):

var slider = d3.select('body')
  .append('p')
  .text('Title: ')
  .attr("class","slider");

slider.append('label')
    .attr('for', 'threshold')
    .text('');
slider.append('input')
    .attr('type', 'range')
    .attr('min', 0)
    .attr('max', 100)
    .attr('value', 50)
    .attr('id', 'threshold')
    .style('display', 'block')
    .on('input', function () {
        var threshold = this.value;
       slider.style("top",threshold+"px");

        d3.select('label').text(threshold);

})
.slider {
  position: absolute;
  left: 100px;
  top: 50px;
  width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

另一种方法是创建一个基于svg的滑块并使用它,使用示例中的transform方法。

d3Noob的d3 tooltip是在svg元素上动态放置html元素的一个很好的例子。请记住,您需要知道svg相对于页面的位置才能正确设置偏移量。

相关问题