preface

I recently encountered a need to add a connector to a tree structure filter to enhance readability while beautifying it.

In the line on the left side of the figure below, the main difficulty is that the height of child elements changes dynamically, and the middle should always be taken as the horizontal reference

Scheme and Implementation

When I saw the function of wiring, the first thought I had was to draw on canvas. However, when I realized that the code of our business had been completed long ago, it was necessary to adjust the code using canvas, which was a lot of work and a little redundant.

The second solution is to use JS to calculate. After the page rendering is completed, the label information is obtained, the height of the line is calculated and other information is drawn directly outside the original label through JS. This scheme is much smaller than the cost above, but the overhead of adding and deleting DOM using JS is not small, and we support the attribute structure of infinite recursion, the hierarchy is too deep and too many tags are likely to cause page blocking;

After weighing the advantages and disadvantages of various schemes, the following measures were adopted:

Train of thought

  1. The child elements themselves draw left horizontal lines, and the parent tag provides vertical lines strung together to form the initial structure

  2. After the first step, the problem is that the vertical bar corresponding to the first and last labels is out of range, so we need a solution here.

    The scheme adopted here is to generate an element block at the upper and lower corners of the corresponding element respectively to cover the excess lines

    Then set the mask block to the corresponding color can be hidden

Code implementation

Horizontal lines for the child element itself and vertical lines for the parent element

Add an element with the pseudo element, then use the absolute positioning and cSS3 displacement attributes

.father {
    position: relative;
    &::after {
      content: "";
      display: inline-block;
      height: 0.5px;
      width: 28px;
      background-color: #dddddd;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translate(-100%, -50%);
    }
}
Copy the code

Mask block implementation

Similar to the above, the difference is that we need to consider more situations, such as background color, offset, etc. Here we can use less Mixins, the specific code can refer to the source code at the bottom

conclusion

The advantage of this approach is that there is no need to refactor the code, CSS writing style is more resource efficient than JS calculation;

However, the disadvantage may be that the accuracy is not very accurate, and if you need to draw lines with rounded corners, it may not be very easy to do

The main point here is to provide an idea

Making the address