首页 > 解决方案 > 有没有办法在javascript中围绕“整个”和“仅”跨度绘制边框?

问题描述

(图一)我想要什么

(图2)我不想要的

(图3)我不想要的

<!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>

我想绘制包含“整个”和“仅”文本跨度的边框(图 1),既不是每一行文本(图 2),也不是矩形框(图 3)。

但是,似乎没有办法正确地做到这一点。我想出的唯一方法如下。

  1. 获取跨度顶点的坐标。例如,

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

  1. 沿着rects画布画线。

但是,这种方法对我来说太乱了。

有没有更好的办法?

标签: javascripthtmlcssborder

解决方案


一个没有透明度但仅使用 CSS 的 hacky 想法。这不是一个非常强大的解决方案,因为您可能需要根据您的实际字体和其他属性调整不同的值。

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>


推荐阅读