繁体   English   中英

在特定字符处断词

[英]Break word at specific character

我意识到有人问过类似的问题,但没有一个像这样。

我有一种情况,我使用 BEM 在code标签中显示一些类。 下面是一个例子:

在此处输入图片说明

显然,默认行为是在连字符处断词,正如我们在示例中看到的那样。 有没有办法可以控制换行符出现在哪些字符上? 我希望能够保持类名的完整性,以便在每个句点之前出现换行符. 如有必要。

不幸的是,我认为没有办法用纯 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM