首页 > 解决方案 > 努力定位使用 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>

如果你觉得它更容易,这是我的CodePenhttps ://codepen.io/fergos2/pen/bGGrqbr

标签: javascriptjqueryhtmlcsspositioning

解决方案


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.


推荐阅读