繁体   English   中英

使用 d3.js 滚动时如何将 x 轴保持在固定位置?

[英]How to keep x-axis in fixed position while scrolling using d3.js?

我有一个 d3 矩阵,带有 x 和 y 轴。 我的 y 轴很长,所以我希望在滚动时仍能看到我的 x 轴。 我想要“固定”位置。 但是添加 .style("position", "fixed") 似乎并不能解决问题。 简单来说,我想做 excel 在冻结行/列时所做的事情。

我有代码:

  var columnLabels = svg.append("g")
  .selectAll(".columnLabelg")
  .data(columnLabel)
  .enter()
  .append("text")
  .text(function(d) { return d; })
  .attr("x", function(d, i) { return i * cellSize; })
  .attr("y", -1)
  .style("text-anchor", "right")
  .attr("transform", function(d, i) { 
      return "translate(" + i + ",-6)"
             + "rotate(300 "+ i * cellSize + " " + (-6) +")"; })


  .attr("class",  function (d,i) { return "columnLabel mono c"+i;} )
  .on("mouseover", function(d) {d3.select(this).classed("text-hover",true);})
  .on("mouseout" , function(d) {d3.select(this).classed("text-hover",false);}) 
  ;

这样做的一个好方法是创建一个标题 div,然后在整个滚动过程中将其粘贴在屏幕顶部。 如果你使用像 scrollmagic 这样的东西,你可以在其中显示你喜欢的任何东西,保持粘性,并正常滚动矩阵的其余部分,这需要一些额外的 JavaScript。

例如,如果您创建一个容器 div,在其中添加列标签,并将其固定到屏幕顶部,则一切正常。

例如:

 var labelContainer = d3.select("div.label-container") //Let's pretend that you've create the labels thus: var columnLabels = labelContainer .selectAll(".columnLabel") .data(columnLabel) .enter() .append("div") .attr("class", "label") //Now let's create a scrollmagic scene, the duration of which will let you set the length during which the element is sticky on scroll. var controller = new ScrollMagic.Controller(); $(function() { // wait for document ready // build scene var scene = new ScrollMagic.Scene({ triggerElement: "#trigger1", duration: 300 }) .setPin("#pin1") .addIndicators({ name: "1 (duration: 300)" }) // add indicators (requires plugin) .addTo(controller); });
 <div id="trigger1" class="label-container"> <div class="label"></div> <div class="label"></div> </div> <div class="svg-container"> <svg class="svg-viz"></svg> </div>

也就是说,除了加载 d3,您还需要加载 Scrollmagic 和 jquery 库:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>

此外,您可能希望使用以下 scrollmagic 库添加指示器以显示场景的开始和结束位置:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/debug.addIndicators.min.js"></script>

您可以在此处阅读有关 scrollmagic 固定的更多信息: http ://scrollmagic.io/examples/basic/simple_pinning.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM