使用jquery更改svg中的线条尺寸

时间:2016-03-09 01:43:38

标签: jquery svg scroll

我有这个svg,它描绘了一个简单的界限:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="80px" height="100px" viewBox="0 0 80 589" enable-background="new 0 0 80 589" xml:space="preserve">

 <line fill="none" stroke="#000000" stroke-linecap="round" stroke-linejoin="round" x1="0" y1="0" x2="1000" y2="1500"/>

</svg>

我希望能够将x1,y1,x2和x1更改为网站滚动位置的函数。我被卡住了,因为我只能改变css属性,而这些不是。

我正在尝试这些方面:

$(window).scroll(function() {
    //calculate how far down the page the user is 
    var $percentageComplete = (($(window).scrollTop() / ($("html").height() - $(window).height())) * 100);
    var svgContainer = d3.select("body").append("svg")
      .attr("width", 200)
      .attr("height", 200);

    var line = svgContainer.append("line")
      .attr("x1", 15)
      .attr("y1", '' + $percentageComplete + '')
      .attr("x2", 30)
      .attr("y2", 20);
    document.getElementById("currentValue").innerHTML = $percentageComplete;

  });
  console.log("Ready");
});

这不起作用,我能够滚动并改变一个值,因为我去了网站,但是当我想要将线的坐标作为滚动的函数时,我有点卡住了

感谢。

2 个答案:

答案 0 :(得分:2)

就我而言,我正在使用c3.js,但我认为它与d3图表相同。

$.each($x_axis, (i, el) => {
                    $(el).find('.tick > text').attr("style", "text-anchor: start;").attr("style", "display: block;").attr("style", "transform: rotate(90deg) translate(15px, 0px);");
                    let $ticks = $(el).find('.tick');
                    $.each($ticks, (j, els) => {
                        var temp = $(els).attr('transform').split(' ');
                        var origin_transform = temp[0].slice(0,-1);
                        $(els).attr('style', 'opacity: 1;').attr('style', 'transform: ' + origin_transform + "px, -4px);");
                        $(els).find('line').attr('y2', '8');
                    });
                });

attr('y2','8')正常工作!

答案 1 :(得分:0)

你问题中的代码是d3,而不是jQuery。但假设你问的是jQuery,它还没有(还)与SVG配合得很好。但是,这应该有效:

$('line')[0].setAttribute('y1', newY1);

或简单的JS:

document.querySelector('line').setAttribute('y1', newY1);