如何使用CSS隐藏类中的特定文本?

时间:2018-12-11 23:27:46

标签: css hide

我有以下内容:

<h4 class="modal-title">Algebra I, Algebra II (2 free spaces)</h4>

我只希望隐藏“(2个自由空间)”,但仍显示其余部分。我该如何仅利用CSS?

最终结果应仅显示“代数I,代数II”。

4 个答案:

答案 0 :(得分:0)

您可以这样做。

<h4 class="modal-title">Algebra I, Algebra II <span style="opacity:0;">(2 free spaces)</span></h4>

此代码将隐藏“(2个自由空间)”。

答案 1 :(得分:0)

您可以通过使整个文本不可见,然后使用:before或:after

重写它来完成此操作

此技术代替了整个文本,而不仅仅是其中一部分。但是,是的,我无法使用CSS替换文本。检查:

.modal-title {
 font-size:0px;
}
.modal-title:before {
 font-size:12px;
 display:inline-block;
 content: "Algebra I, Algebra II"
}

答案 2 :(得分:0)

您可以在(2 free spaces)周围添加一个class跨度,以便可以在CSS中对其进行引用:

<h4 class="modal-title">Algebra I, Algebra II <span class="hide">(2 free spaces)</span></h4>

然后,在CSS中,您可以使用class定位跨度的display: none来隐藏它:

.hide {
  display: none
}

请参见下面的工作示例:

.hide {
  display: none;
}
<h4 class="modal-title">Algebra I, Algebra II <span class="hide">(2 free spaces)</span></h4>

如果您无法在HTML中添加跨度或不知道标题的大小,则可以使用以下javascript:

let modal_title = document.querySelectorAll('.modal-title'); // get the modal title elements

modal_title.forEach(elem => { // loop over each element, where elem represents a given modal title
  let txt_title = elem.textContent; // get the text from that given modal title
  elem.innerHTML = txt_title.replace(/(\(\d+ free spaces\))/, "<span class='hide'>$1</span>"); // add the "hide" span around the title text using regex
});
.hide {
  display: none;
}
<h4 class="modal-title">Algebra I, Algebra II (2 free spaces)</h4>

<h4 class="modal-title">Alg I, Alg II (10 free spaces)</h4>

答案 3 :(得分:0)

如果知道字体属性,则可以使用固定宽度将其隐藏,以便可以定义正确的宽度:

.modal-title {
  width:148px;
  overflow:hidden;
  white-space:nowrap;
}
<h4 class="modal-title">Algebra I, Algebra II (2 free spaces)</h4>

如果您要隐藏的文本始终相同,您也可以尝试以下操作:

.modal-title {
  display:inline-block;
  position:relative;
  margin-right:-80px;
}
.modal-title:after {
  content:"";
  position:absolute;
  right:0;
  top:0;
  bottom:0;
  width:100px;
  background:#fff;
}
<h4 class="modal-title">Algebra I, Algebra II (2 free spaces)</h4>
<h4 class="modal-title">Algebra I (5 free spaces)</h4>
<h4 class="modal-title">Alg I, Alg II (2 free spaces)</h4>