2017-06-13 17 views
1

我有代碼滑塊:移動滑塊D3對象具體位置

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」)進行分組,但我無法將其與當前代碼進行集成。

回答

2

您的滑塊不是svg的一部分,它包含附加到主體的非svg元素。像這樣的轉換是用於svg元素,而不是用於非svg html元素。您需要像使用CSS一樣更新元素的位置。

您引用的示例通過使用svg元素來模擬滑塊來創建svg滑塊。滑塊包含一個SVG g元素中,因此可以使用.attr("transform","translate(x,y)")

您可以將您的滑塊與使用CSS任何其他HTML /非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是html元素動態放置在svg元素上的一個很好的例子。請記住,您需要知道svg相對於頁面的位置,才能正確設置偏移量。