[英]Break word at specific character
不幸的是,我认为没有办法用纯 CSS 做你想做的一切。
更新:在 JS 解决方案中删除了句点之前的空格。
如果您能够使用 JavaScript,您可以处理code
标记的内容以禁用带连字符的单词包装,并且您可以在内inline-block
跨度中以句点开头包装每个块。
以下代码将每个code
标记的内容分解为以空格或句点开头的块列表。 每个块都用一个跨度包裹,以防止包裹,以句点开头的块额外标记为display: inline-block;
. 这应该提供您正在寻找的行为,并在复制粘贴文本时另外保留所有内容。
CSS:
.no-wrap-hyphen {
white-space: nowrap;
}
.wrap-period {
display: inline-block;
}
JavaScript(在窗口加载和调整大小时运行此函数):
function wrapPeriodsNotHyphens() { // run on window load or resize
var codes = document.getElementsByTagName( "code" );
for ( var i = 0; i < codes.length; i++ ) {
currentCode = codes[ i ].innerHTML.split(/(?=[ .])/); // split by spaces and periods
for ( var c = 0; c < currentCode.length; c++ ) {
// surround each item with nowrap span
currentCode[ c ] = '<span class="no-wrap-hyphen">' + currentCode[ c ] + '</span>';
if ( currentCode[ c ].indexOf( '.' ) > -1 ) {
// add a zero size space at the start for periods
currentCode[ c ] = '<span class="wrap-period">' + currentCode[ c ] + '</span>';
}
}
codes[ i ].innerHTML = currentCode.join('');
}
}
我有另一个使用 jquery 的解决方案,
$('.mypara').each(function () { var str = $(this).html(); var htmlfoo = str.split('.').join('</br>'); $(this).html(htmlfoo); });
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <code class="mypara"> This is-the HTML if its - characters exceed 50. characters it should go-to next line </code> <code class="mypara"> This is the HTM-if its. characters exceed 50 - characters it should. go-to next-line </code>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.