How to hide some text in string using CSS
请找到更新的代码
1 2 3 4 5 6 7 8 9 10 11 12 | <html> css <head> <style> #st { z-index: -114; margin-right: -80px; } </style> </head> State Code : <span><span id="st"></span>Maharashtra - MH</span> </html> |
我的输出低于输出,但是我需要清楚的重叠文本
在此处输入图片说明
解决此问题的唯一方法是使用CSS显示:无或可见性:隐藏属性,无论哪种都可以,我建议不显示。这是CSS和HTML可以隐藏数据的唯一方法。
1 | <span>State Code: <span id="st"><span style="display: none">Maharashtra - </span>MH</span></span> |
看到这是HTML版本,但工作正常。
1 2 3 4 5 6 7 8 9 | <span id="span_Id">Maharashtra - MH</span> function getSecondPart(str) { return str.split('-')[1]; } var span_Text = document.getElementById("span_Id").innerText; var html = getSecondPart(span_Text); document.getElementById("span_Id").innerHTML = html; |
您不能仅使用CSS来执行此操作,这是您的javascript解决方案
1 2 3 4 5 | $("#st").html(function(){ var text= $(this).text().trim().split(""); var first = text.shift(); return (text.length > 0 ?"<span class='hide'>"+ first +"</span>" : first) + text.join(""); }); |
1 2 3 | .hide { display:none; } |
1 2 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <span>State Code: <span id="st">Maharashtra - MH</span></span> |
更新2
布局已发生重大变化...请参阅第二个更新的演示。
由于OP具有动态生成的文本,因此实际上需要JavaScript。实际的文本可能会在页面上超过一个。
-
该演示收集了嵌套在
中的所有 (可以使用 #id ,但实际上,它应该是.class )。此NodeList转换为数组。 -
然后在每次正则表达式与
文本匹配的迭代中,对该数组进行 map() 操作。 -
文本不需要部分的
replace() '覆盖,并且保留最后2个字母。
演示版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var tgt = Array.from(document.querySelectorAll('span')); tgt.map(function(s, idx) { var str = s.textContent; var rgx = /(State Code:).*?- (\\w\\w)/g; var rep = `$1 $2`; var res = str.replace(rgx, rep); s.textContent = res; }); |
1 2 3 4 | <span>State Code: <span class="st"></span>California - CA</span> <span>State Code: <span class="st"></span>New York - NY</span> <span>State Code: <span class="st"></span>Oregon - OR</span> <span>State Code: <span class="st"></span>Mississippi - MS</span> |
如果您使用PHP,请在下面尝试。
1 2 3 | $string = explode("-","Maharashtra - MH"); <span>State Code: <span id="st"><span style="display:none;"><?php echo $sting[0]."-"; ?></span><?php echo $string[1]; ?></span></span> |