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

问题描述 投票:0回答:2

我有两个不同的textareas,两个最大maxlenghts。仅当一个文本区域成为焦点时,才会显示每个文本区域的字符计数,即两个文本区域的字符计数不会同时显示。该代码工作正常。但是,由于工作的缘故,我正在努力创建如下的柜台样式:

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

由于它不在h​​tml代码中,因此我无法通过绝对定位等方式正确设置其样式。如果我确实在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

javascript jquery html css positioning
2个回答
2
投票

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

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

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

让我知道是否可以。


0
投票

而不是用$this.parent().after($counter);$this.parent().append($counter);放在.textbox中

然后只需使用定位将其放置在所需位置即可:

.textbox {
  position: relative;
}

.counter {
  position: absolute;
  right: 15px;
  bottom: 5px;
}
© www.soinside.com 2019 - 2024. All rights reserved.