使用点击函数jquery更改svg图像的描边宽度

3

当用户单击按钮时,我想将svg图像的描边宽度增加0.5。我已经有了单击函数,但不确定如何使函数起作用以增加描边宽度。

function pipeScaleFactorPlus(){
    $(".pipe").style("stroke-width", "+=0.5");

  drawMapPipes();    
}

.pipe是SVG类,调用drawMapPipes()函数重新绘制SVG图像。


你能创建一个 [mcve] 吗?即使它有错误,我们也可以运行它。 - Robert Longson
你还需要什么,比如点击功能吗?因为我正在从数据库中提取svg以在地图上创建管道,所以很难在codepen.io或其他地方创建示例。 - lostInTheTetons
你的示例不需要复制数据库的内容,只需要有一个预先创建的对象,你可以尝试调整它的笔画宽度。 - Robert Longson
另外,jQuery没有style()函数。您是否使用了其他添加该函数的插件? - Paul LeBeau
2个回答

4
假设您只使用普通的jQuery。下面是如何调整描边宽度的方法。
请注意,我们必须进行一些额外的修改来修改一些SVG属性,因为某些属性的名称与样式属性名称不同。
例如,该属性的名称为stroke-width,但style属性为strokeWidth。

$("button").click(function(evt) {
  var myLine = $("line");
  // Get the current stroke-width.
  // Try getting it from the style object first. Otherwise get it direct
  // from the attribute value.
  // We use parseInt() to strip off any units ("20px" -> 20)
  var currentWidth = parseInt(myLine.css("strokeWidth") || myLine.attr("stroke-width"), 10);
  // Update the style property "strokeWidth".
  // Note that the property has a different spelling to the attribute.
  myLine.css("strokeWidth", 30 - currentWidth);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg>
  <line y1="75" x2="300" y2="75" stroke="black" stroke-width="10"/>
</svg>

<button>Click me</button>


1
我明白了。我试图让它变得比必要的更加复杂。我只需创建一个新变量并设置描边宽度,然后在单击函数中添加函数即可。
    $("#increasePipe").click(function(){
      map.pipeSize += 0.25;
        if (map.pipeSize > map.pipeSizeMax){
            map.pipeSize = map.pipeSizeMax;
        }
      map.svg.selectAll(".pipe").style("stroke-width", map.pipeSize);
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接