首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有环绕行的动态文本,其容器具有背景图像

问带有环绕行的动态文本,其容器具有背景图像
EN

Stack Overflow用户
提问于 2014-11-29 13:32:17
回答 2查看 33关注 0票数 0

我需要实现像这样的东西..

代码语言:javascript
复制
-------------------------
|                        |
|                        |
|----  dynamic text  --- |
|                        |
-------------------------

我想在css中的“动态文本”周围的线。

我尝试使用css之前的&::和css之后的&::,但当动态文本发生变化时,我仍然需要对其进行拉伸/缩小。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2014-11-29 14:04:06

您可以使用JavaScript动态设置:before和:after:伪元素的宽度。

​

代码语言:javascript
复制
function foo() {
  var ss = document.styleSheets;
  var text = document.getElementById('text');
  var box = document.getElementById('box');
  var totalWidth = getComputedStyle(box).width.slice(0, -2);
  var textWidth = text.offsetWidth;
  var lineWidth;
  var margin = 4;  // Set the margin between text and line.

  for (i = 0; i < ss.length; i++) {
    var rules = ss[i];
    for (j = 0; j < rules.cssRules.length; j++) {
      var r = rules.cssRules[j];
      if (r.selectorText == "#text:before") {
        // If you want the margin to be set on both sides of the line,
        // replace 'margin' with '(margin * 2)' in the next line.
        lineWidth = ((totalWidth / 2) - (textWidth / 2) - margin);
        r.style.width = lineWidth + 'px';
        r.style.left = -(lineWidth + margin) + 'px';
      } else if (r.selectorText == "#text:after") {
        r.style.width = lineWidth + 'px';
        r.style.right = -(lineWidth + margin) + 'px';
      }
    }
  }
}
foo();
代码语言:javascript
复制
#box {
  width: 300px;
  height: 200px;
  background-color: #FF0000;
  line-height: 200px;
  text-align: center;
}
#text {
  position: relative;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 10px;
  padding: 4px;
  color: white;
}
#text:before {
  content: "";
  position: absolute;
  border-bottom: 1px solid black;
  height: 100px;
}
#text:after {
  content: "";
  position: absolute;
  border-bottom: 1px solid black;
  height: 100px;
}
代码语言:javascript
复制
<div id="box"><span id="text">This is the text which is dynamic</span>

</div>

​

票数 1
EN

Stack Overflow用户

发布于 2014-11-29 13:48:47

代码语言:javascript
复制
<div id="divWithBackground">

  <div id="divActsAsLine">

    <span id="DynamicText">Your text here </span>

  </div>

</div>

现在是CSS

代码语言:javascript
复制
#divActsAsLine{
border-botton:1px solid #00;
text-align:center;
}

#DynamicText{
 position:relative;
 background-color: #fff;
 margin-bottom:-20px /*Adjust this based on your requirements*/
 z-index:1 /* optional */
}

其逻辑是使div边距作为背景行,并使跨度与此行重叠,为此,我们需要减少或增加边距属性。如有必要,可能需要使用z-index

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27199225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档