javascript 如何在不替换文本的情况下在 div 上画一条线,在文本上画一条线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14283281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:13:02  来源:igfitidea点击:

How can I draw a line across a div, over text, without displacing the text?

javascripthtmlcss

提问by user1790093

I have a series of square divs with text in them, and I need to draw a line across those divs, over the text. Z-Index is not an option. Neither is <strike>, because it needs to extend across the entire div, not just the text.

我有一系列带有文本的方形 div,我需要在这些 div 上在文本上画一条线。Z-Index 不是一个选项。也不是<strike>,因为它需要扩展到整个 div,而不仅仅是文本。

What I need is for it to extend across the entire div, but to be ON TOP of the text, as if on a different layer, and I am trying to determine if it is possible without Z-Index.

我需要的是它扩展到整个 div,但要位于文本的顶部,就像在不同的层上一样,我试图确定没有 Z-Index 是否可能。

回答by Zoltan Toth

With the help of :after- DEMO

借助:after- DEMO

div {
    position: relative;  
}

div:after {
  position: absolute;
  left: 0;
  top: 50%;
  height: 1px;
  background: #c00;
  content: "";
  width: 100%;
  display: block;
}

回答by Muhammad Talha Akbar

Link To Fiddle

链接到小提琴

.wrapper {
  position:relative;
  width:110px;
}
.square {
  width:20px;
  height:20px;
  border:2px solid #000;
  display:inline-block;
  text-align:center;
}
.strike {
  position:absolute;
  width:100%;
  height:2px;
  background:black;
  top:11px;
  left:0px;
}

回答by Honorable Chow

If you can't use text-decoration:line-through it's likely you have padding or margin on your div which is why the line doesn't go all the way across. This snippet will draw a line the width of the div and through the text preserving your padding or margins.

如果您不能使用 text-decoration:line-through,则 div 上可能有填充或边距,这就是该行没有完全穿过的原因。此代码段将绘制一条 div 宽度的线,并穿过保留填充或边距的文本。

<div style="border:solid 2px black; padding : 100px">
       <div class="strike-through" style="border-bottom : solid 1px red; margin-bottom : -12px;"></div>
       <div style="text-align : center; padding-left:50px; padding-right:50px; border : solid 1px green;">Lorem Ipsum Voluptatem</div>
  </div>

回答by J?rg velletti

what about a background image as a solution? I mean someCSS Code like:

作为解决方案的背景图像怎么样?我的意思是一些CSS代码,如:

.DIV.squarestroke {
 background: url(img_with-line.gif) repeat;
}

回答by Steve Wellens

A good old fashion hr might do it:

一个好的旧时尚 hr 可能会这样做:

 <hr style="position:absolute; width:50px; top:5px; left:5px;" />