javascript - 努力定位使用 jQuery 创建的 div 元素

标签 javascript jquery html css positioning

我有两个不同的文本区域和两个不同的最大长度。每个文本区域的字符数只会在其中一个文本区域处于焦点时显示,即两个文本区域的字符数不会同时显示。该代码工作正常。但是,我正在为柜台的样式而苦苦挣扎,因为它是按照以下目的创建的:

$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

最佳答案

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

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

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

如果没有,请告诉我。

关于javascript - 努力定位使用 jQuery 创建的 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58606822/

相关文章:

Javascript toFixed() 不是函数

html - 制作两列,每列有 2 张图片

javascript - 如何在 Node 服务器上运行 .bat 文件?

javascript - 当我使用 AngularJS 部分时如何让 JQuery 工作?

javascript - date.getTime 在 cookie 的过期标志中的用途?

javascript - ES6中的静态导入是什么意思?

php - 将参数传递给 jquery javascript 函数?

javascript - Jquery 在我的网站上不起作用

javascript - 图像周围有可笑的灰色边框

javascript - IE 上没有图像只有带白色 x 的黑框