简体   繁体   中英

How to cursor-select SVG/d3.js text just like normal HTML text or any other text editor?

I'm using d3.js to draw a layout graph like this one: https://bl.ocks.org/mbostock/950642

But I found that it's very difficult to copy-and-paste the node's label. Take the above link as an example, I can't drag the text to select any sequence. I can only double-click the label to select a certain char sequence.

If I try to select the text with a special char like Mlle.Vaubois , I can only get Mlle or Vaubois selected, I cannot get the whole string Mlle.Vaubois selected. (See the below picture)

在此输入图像描述

Moreover, I can't select arbitrary char sequence inside that string. For example, I can't select the middle two letters: ll inside Mlle.Vaubois . The highlighting stopped right after the first l is selected. (See below:)

在此输入图像描述

I just want to be able to select any sequence as I want, like in a browser. For example, I can select rce La from the HTML text: Labeled Force Layout as below. Then I can Ctrl + C and Ctrl + V as I wish.

在此输入图像描述

This issue is not just for d3.js, because another more general SVG example also has this issue: http://jsfiddle.net/wPYvS/

在此输入图像描述

I don't know why SVG handles text selection so different with normal HTML text in a browser or any mainstream text editor? How to solve it? Thanks.

The following example adds a click handler to all the "nodes" (ie. class="node" ), which will select all the text in the node.

 var nodes = document.querySelectorAll(".node"); nodes.forEach( function(elem) { elem.addEventListener("click", nodeClickHandler); }); function nodeClickHandler(evt) { var selection = document.getSelection(); var range = selection.getRangeAt(0); range.selectNode(evt.target); } 
 <svg width="500" height="200"> <g class="node" transform="translate(275.4819543667187,131.9805407488932)"> <image xlink:href="https://github.com/favicon.ico" x="-8" y="-8" width="16" height="16"> </image> <text dx="12" dy=".35em">Mlle.Vaubois</text> </g> </svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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