【发布时间】:2019-07-18 16:01:58
【问题描述】:
我正在创建一条线(路径),当它被点击时会改变颜色。为了改变颜色,我添加了class。此操作还将充当将类从一条路径(线)切换到另一条路径(线)。
下面是我的工作代码。
public drawLines() {
this._containerSvg.append( 'line:defs' ).append( 'line:marker' )
.attr( 'id', 'triangle' )
.attr( 'refX', 6 )
.attr( 'refY', 6 )
.attr( 'markerWidth', 30 )
.attr( 'markerHeight', 30 )
.attr( 'markerUnits', 'userSpaceOnUse' )
.attr( 'orient', 'auto' )
.append( 'path' )
.attr( 'd', 'M 0 0 12 6 0 12 3 6' )
.style( 'fill', 'black' );
this._containerSvg.selectAll( 'line' )
.data( this._connectLines, ( line : Line ) => {
return line.id
} )
.enter()
.append( 'line' )
.attr( 'id', ( line : Line ) => line.id )
.attr( 'x1', ( line : Line ) => line.x1 )
.attr( 'y1', ( line : Line ) => line.y1 )
.attr( 'x2', ( line : Line ) => line.x2 )
.attr( 'y2', ( line : Line ) => line.y2 )
.style( 'stroke', 'black' )
.style( 'stroke-width', '4px' )
.style( 'cursor', 'pointer' )
.attr( 'marker-end', 'url(#triangle)' )
.on( 'click', ( line ) => {
this._selectedLine = line;
this.updateLines();
} );
}
updateLines() {
this._containerSvg.selectAll( 'line' )
.data( this._connectLines, ( line : Line ) => {
return line.id;
} )
.attr( 'x1', ( line : Line ) => line.x1 )
.attr( 'y1', ( line : Line ) => line.y1 )
.attr( 'x2', ( line : Line ) => line.x2 )
.attr( 'y2', ( line : Line ) => line.y2 )
.attr( 'class', ( line : Line ) => this._selectedLine === line ? 'selected' : '' )
}
CSS 文件。
svg line.selected {
stroke: green !important;
}
无论何时选择该行,它都会将其更改为绿色,而不是箭头。选择行时如何更改箭头的颜色?
提前致谢。
【问题讨论】:
-
您不能那样设置标记实例的样式。如需解释,请查看我的 answer 至 "Click event does not work on the mark-end of path in SVG"。
-
Change color of marker-end on mouseover 的可能重复项。简短但恰到好处。
-
延伸阅读:"Changing an SVG marker's color - CSS?"。正如 Erik Dahlström 的 answer 中所解释的,
<marker>元素只能从其祖先继承样式,而不是其引用元素。不幸的是,这排除了 Sara Soueidan 在她的文章 Styling SVG <use> Content with CSS 中为<use>元素提出的巧妙方法。
标签: javascript css angular d3.js