我有这个div使用text-transorm: capitalize
:
<div style="display: flex;align-items:center; width: 400px; justify-content: space-between ; max-width: 100%;">
<p style="margin: 10px 0">Title</p>
<input type="text" id="titleInput" style="width: 300px; text-transform: capitalize;"
onkeyup="getIputValue(`titleInput`, `title`)" />
</div>
我需要找到一种方法(可能添加一个if语句)来为一些单词(如"of")而不是"of"。你的建议是什么?
我想使用这个函数,但它不起作用。我知道我错过了一些东西:
function lowerCasedWords() {
let text = document.getElementById('titleInput').value;
if (text.includes('Of') === 'true'){
text.replace('Of', 'of')
}
}
首先你不能"CSS和Javascript。如果你不把text-transform: capitalize;
移到input
上不管你的函数做什么。因为你想要排除一些单词,所以最好使用JS。
其次,输入值需要在每次按下一个键(或者每次按空格键)时更新。
最后在你的函数中,用'Of'替换'Of'是不够的,你需要替换你输入的value属性。
下面是一个工作示例
const input = document.getElementById('input');
const capitalize = word => {
return word ? word[0].toUpperCase() + word.substr(1).toLowerCase() : '';
}
const noCapNeeded = ['of', 'a'];
input.addEventListener('input', evt => {
input.value = input.value.toLowerCase().split(' ').map(word => {
return noCapNeeded.includes(word)
? word
: capitalize(word);
}).join(' ');
});
<input type="text" id="input">