Search code examples
javascripthtmlcssborder

Is there any way to draw border around 'whole' and 'only' span in javascript?


(figure 1) What I want

(figure 2) What I don't want

(figure 3) What I don't want

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
</head>
<body>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
    <span>Lorem Ipsum has been the industry's standard dummy text ever since the
     1500s, when an unknown printer took a galley of type and scrambled it to make a
     type specimen book.</span> It has survived not only five centuries, but also
     the leap into electronic typesetting, remaining essentially unchanged. It was 
    popularised in the 1960s with the release of Letraset sheets containing Lorem 
    Ipsum passages, and more recently with desktop publishing software like Aldus 
    PageMaker including versions of Lorem Ipsum.</p>
</body>
</html>

I want to draw borders which wraps 'whole' and 'only' span of text (figure 1), neither each line of text(figure 2) nor rectangular box(figure 3).

But, it seems that there is no way to do it properly. The only method I came up with is below.

  1. Get coordinates of vertices of span. For example,

rects = getElemmentByTagName("span")[0].getClientRects()

  1. Draw lines along the rects on canvas.

But, this method feels too messy to me.

Is there any better way?


Solution

  • a hacky idea without transparency but using CSS only. Not a very robust solution as you may need to adjust the different values based on your actual font and other properties.

    span {
      background:#fff;
      box-shadow:
       0 -2px 0 0 #fff,
       0 0 0 2px red;
      position:relative;
      -webkit-box-decoration-break: clone;
      box-decoration-break: clone;
    }
    span::before {
      content:"";
      position:absolute;
      top:-2px;
      left:0;
      width:100vw;
      height:2px;
      background:red;
    }
    span::after {
      content:"";
      position:absolute;
      top:calc(1.2em - 2px); /* you many need to update the 1.2em based on your font */
      right:100%;
      width:100vw;
      height:2px;
      background:red;
    }
    
    
    p {
      margin: 80px 0;
      text-align: justify;
      font-size: 22px;
      overflow:hidden;
      padding:2px;
    }
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
      <span>Lorem Ipsum has been the industry's standard dummy text ever since the
         1500s, when an unknown printer took a galley of type and scrambled it to make a
         type specimen book.</span> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
      and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>