在已大写的字符串中将少数选定的单词设置为小写

问题描述 投票:3回答:2

我正在寻找这个问题的解决方案一段时间。我在段落标记中有一个句子和一个类,它将此标记中的文本变为大写,我希望只有几个单词保留为小写并且保持大写格式

<p class="words">this Is A Text That needs To Be Formatted</p>

<!--css-->

.words{text-transform:capitalize}

所有我想要的是像“是”“一个”“到”以保持小写格式并使用jquery或javascript在标题情况下休息,请记住,文本默认情况下写在标题大小写中,例如像这样

<p class="words">This is a Text That Needs to Be Formatted</p>
javascript jquery html
2个回答
2
投票

使用带有自定义样式(或使用公共类)的span标记来包装它们以转换小写。

// use html() method with a callback to iterate over if there is multiple
// then replace needed words with a wrapped span element

$('p.words').html((_, html) => html.replace(/\b(?:is|a|to)\b/ig, '<span style="text-transform:lowercase">$&</span>'))
.words {
  text-transform: capitalize
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="words">this Is A Text That needs To Be Formatted</p>

普通班级:

// use html() method with a callback to iterate over if there is multiple
// then replace needed words with a wrapped span element

$('p.words').html((_, html) => html.replace(/\b(?:is|a|to)\b/ig, '<span class="lower">$&</span>'))
.words {
  text-transform: capitalize
}

.lower{
  text-transform: lowercase
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="words">this Is A Text That needs To Be Formatted</p>

或者,如果您没有使用text-transform样式到.words,那么只需用小写本身替换。

// use html() method with a callback to iterate over if there is multiple
// then replace needed words with a wrapped span element

$('p.words').html((_, html) => html.replace(/\b(?:is|a|to)\b/ig, m=>m.toLowerCase()))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="words">this Is A Text That needs To Be Formatted</p>

仅供参考:使用html()方法更新HTML内容将重新创建标记内的所有DOM元素,因此嵌套元素的任何附加事件处理程序将不再起作用。


1
投票

使用范围:

<p class="words">This <span class="lowercase">Is</span> A Text That Needs <span class="lowercase">To>/span> Be Formatted</p>

我不认为还有另一个解决方案只使用html / css

© www.soinside.com 2019 - 2024. All rights reserved.