0 x0. Effect
First, the renderings:
0 x1. Cause
There is a document module in the APP, which is an embedded Web page developed in the front end and supports access in the client and wechat. There is a function called underlined note, which is to mark the selected text after long pressing the text, and this is the background.
In a demand iteration process, the product raised some questions about the underlined note function, such as why the styles of iOS and Android are not unified (using the system’s native long press to select), whether the text can be selected by clicking, whether the style can be customized, and whether the pros and downs can be selected…
Hearing this, my heart is like this
In the spirit of being friendly with the product, I immediately said that these requests were great and THAT I needed to think hard about saying no.
0 x2. Analysis
Of course, the idea is the idea, do or want to find a way to do
From the perspective of product requirements, only the long-press selection of a simulated system can meet the current and future potential requirements of the product. If simulating a long-press selection, the following problems need to be solved:
- You need to disable the system’s long press to select text
- You need to get the exact location of the click character
- You need to be able to simulate the rectangular background when selected
0 x3. Implementation
In view of the analysis just now, we can probably achieve this:
First, add a user-select: None style to disable the system’s text selection directly. Second, the DOM API for obtaining character positions indirectly or directly, probably only indirectly through range.getClientRects ()
Thirdly, there were two schemes originally conceived. One was to insert labels directly into text, which would inevitably change the structure of the whole DOM and affect subsequent tags. Therefore, the second scheme was adopted, which was to add an SVG layer directly and draw through POLYgons and rectangles of SVG
Finally, see github.com/luojilab/ea for specific implementation… We have opened up this solution
This scheme has the following advantages:
- Custom select styles
- Click to select the current sentence
- Long press to select the current sentence
- Forward and inverse selection
- Highlight the selected text
- .
Star, Iusse and PR are welcome if you need them.
The article first appeared in the front of luoji thinking zhihu column, welcome to pay attention.