javascript - 努力定位使用 jQuery 创建的 div 元素
问题描述
我有两个不同的文本区域,有两个不同的最大长度。每个文本区域的字符数只会在其中一个文本区域处于焦点时显示,即两个文本区域的字符数不会同时显示。代码工作正常。但是,我在柜台的样式上苦苦挣扎,因为它是按照以下目的创建的:
$counter = $("<div class='counter'/>");
由于它不在 HTML 代码中,因此我无法使用绝对定位等正确设置它的样式。如果我确实在 HTML 中创建了计数器元素并在 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
解决方案
I updated your code here https://codepen.io/ggrigorov/pen/MWWvRaX
I made one small change to place the counter inside the textbox
. And updated the styles so it can be positioned relative to the textbox
.
There can be other implementations, but this should work.
Let me know if it doesn't.
推荐阅读
- reactjs - 根据服务器中的数据在帖子正文到达服务器之前对其进行变异(Fetch API)
- java - 嵌套异常是 org.hibernate.PersistentObjectException JPA Spring Boot
- c++ - 如何使用字符串文字初始化 const char []
- flutter - Flutter:三列 Row:当左右两列大小不等时,中间列如何居中?
- javascript - 我可以将 math.js 对象转换为 JavaScript 函数吗?
- flutter - NoSuchMethodError: 试图调用一个非函数,比如 null: 't0.changeLang'
- c++ - 如何将多个命令行参数添加到可执行 C++
- mongodb - 表示表达式的对象必须只有一个字段
- angular - ndx-datatable 安装在 Angular 11 对等依赖警告上
- linux - “C 编译器无法创建可执行文件”配置 gcc 时出错