I have two different textareas with two different maxlenghts.
(我有两个不同的文本区域,其中有两个不同的最大像素长度。)
The character count of each textarea will only show up once one of the textareas is on focus, ie the character count of both textareas will not show at the same time.(每个文本区域的字符数仅在其中一个文本区域聚焦时才会显示,即两个文本区域的字符数不会同时显示。)
The code works fine.(该代码工作正常。)
However, I am struggling with the styling of the counter as it is created as followed aiming to work:(但是,我正在努力创造柜台的风格,目的是为了达到以下目的:)
$counter = $("<div class='counter'/>");
As it is not in the HTML code, I am not being able to style it properly with absolute positioning and so on.
(由于它不在HTML代码中,因此无法使用绝对定位等正确设置其样式。)
If I do create the counter element in the HTML and call it's class in jQuery both counters show at the same time and right next to one another which is not what I am aiming for.(如果我确实在HTML中创建了counter元素,并在jQuery中调用了它的类,则这两个计数器会同时显示,并且彼此紧挨着显示,这并不是我想要的。)
I was wondering if you guys could help me.(我想知道你们是否可以帮助我。)
I would like to set the counter in the right bottom corner of its respective textbox.
(我想将计数器设置在其相应文本框的右下角。)
$(function() {
$.fn.textCounter = function() {
//for each
return this.each(function(index) {
//console.log("LocktonAsset"+index);
var $this = $(this),
maxLength = $this.prop("maxlength"),
$counter = $("<div class='counter'/>");
console.log(maxLength);
$this.parent().after($counter);
$this.on("focus", function() {
$counter.addClass("visible");
});
$this.on("blur", function() {
$counter.removeClass("visible");
});
$this.on("keyup", function() {
var val = $this.val(),
currentLength = val.length,
remaining =
(maxLength - currentLength),
safePercent = maxLength * 80 / 100;
$counter.text(remaining);
var color = currentLength <= safePercent ? "blue" : "red";
$counter.css("color", color);
}); //end keyup
}); //end each
}; //end textcounter
$("textarea").textCounter();
});
.textbox {
display: inline-block;
}
.textbox {
background-color: pink;
> textarea {
width: 200px;
height: 50px;
padding: 10px;
}
}
.counter {
display: none;
font-size: 10px;
background-color: yellow;
}
.counter.visible {
display: inline-block;
}
form {
input {
margin-top: 20px;
}
}
<div class="container">
<div class="wrapper">
<!-- First textarea -->
<div class="textbox">
<textarea maxlength="50" placeholder="Write something..."></textarea>
</div>
<!-- Second textarea -->
<div class="textbox">
<textarea maxlength="100" placeholder="Write something..."></textarea>
</div>
<form>
<input type="text" maxlength="10">
</form>
</div>
</div>
If you find it easier, here's my CodePen : https://codepen.io/fergos2/pen/bGGrqbr
(如果您觉得更简单,这是我的CodePen : https : //codepen.io/fergos2/pen/bGGrqbr)
ask by Fergo translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…