我正在编写一个小脚本,以根据在文本框中键入时剩余的可用字符的值来更改某些跨度文本的颜色。
我可以使用计数器显示剩余的字符数,但是当剩余的字符数大于或等于允许的最大字符数时,我似乎无法改变颜色。
这是我的JavaScript代码:
$(document).ready(function(){
var maxChar = 300;
$("textarea").keyup(function() {
var length = $(this).val().length;
var charCount = maxChar - length;
$("#charCount").text(charCount);
if (charCount >= maxChar) {
document.getElementById("charCount").style.color = "#ff3343";
}
})
});
HTML文本框:
<div class="form-group col-12">
<label for="hostDesc">Description</label>
<textarea class="form-control" name="hostDesc" id="hostDesc" min="0" maxlength="300" data-ng-model="hostDesc" aria-describedby="descHelp" placeholder="Leave a description" rows="8" style="height: 150px" required></textarea>
<p class="text-small text-muted mb-0"><span id="charCount">300</span> characters remaining</p>
</div>
答案 0 :(得分:2)
您错误地使用了>=
:
$(document).ready(function() {
var maxChar = 300;
$("textarea").keyup(function() {
var length = $(this).val().length;
var charCount = maxChar - length;
$("#charCount").text(charCount);
if (charCount <= maxChar) {
document.getElementById("charCount").style.color = "#ff3343";
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-12">
<label for="hostDesc">Description</label>
<textarea class="form-control" name="hostDesc" id="hostDesc" min="0" maxlength="300" data-ng-model="hostDesc" aria-describedby="descHelp" placeholder="Leave a description" rows="8" style="height: 150px" required></textarea>
<p class="text-small text-muted mb-0"><span id="charCount">300</span> characters remaining</p>
</div>
希望这会有所帮助,