正在努力定位使用jQuery创建的div元素



我有两个不同的文本区域,它们的最大长度不同。每个文本区域的字符数只会在其中一个文本区域聚焦时显示,即两个文本区域的字符串数不会同时显示。代码运行良好。然而,我正在为柜台的造型而挣扎,因为它是按照以下方式创建的,目的是工作:

$counter = $("<div class='counter'/>");

由于它不在HTML代码中,我无法用绝对定位等方法正确地设置它的样式。如果我在HTML中创建counter元素并在jQuery中调用它的类,两个计数器同时显示,并且紧挨着显示,这不是我的目标。我想知道你们能不能帮我。

我想将计数器设置在相应文本框的右下角。

$(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>

如果您觉得更容易,下面是我的CodePen:https://codepen.io/fergos2/pen/bGGrqbr

我在这里更新了您的代码https://codepen.io/ggrigorov/pen/MWWvRaX

我做了一个小改动,把计数器放在textbox里面。并更新了样式,使其可以相对于textbox进行定位。

可以有其他实现,但这应该有效。

如果没有,请告诉我。

不将$this.parent().after($counter);放入带有$this.parent().append($counter);的.textbox中

然后只需使用定位将其定位到您想要的位置:

.textbox {
position: relative;
}
.counter {
position: absolute;
right: 15px;
bottom: 5px;
}

最新更新