【问题标题】:javascript text field counter displayjavascript文本字段计数器显示
【发布时间】:2015-02-09 14:26:23
【问题描述】:

我正在使用Count textarea characters 此处给出的答案,但需要对其进行修改以对文本字段输入中的字符进行倒计时并在达到某些倒计时数字限制时更改颜色,以向用户提供某种形式的警告接近领域限制。

到目前为止,这是我自己整理的。它确实有效! (惊人地)。首先,这是我开始的:

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        $("#count_4_1").text("Characters remaining: " + (2550 - $(this).val().length));
    });
});

这就是我重新发明的:

$(window).load(function() {
    $("#input_4_1").keyup(function() {
        if (2550 - $(this).val().length >= 501) {
            $("#count_4_1").text("Characters remaining: " + (2550 - $(this).val().length));
        } else if ((2550 - $(this).val().length <= 500) && (2550 - $(this).val().length >= 101)) {
            $("#count_4_1").text("<span style=\"color: #55a500;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
        } else if (2550 - $(this).val().length <= 100) {
            $("#count_4_1").text("<span style=\"color: #ff0000;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
        }
    });
});

这就是惊人的效果。除了一个例外——问题来了。我对JS几乎一无所知。当读取的字符数在 2550 和 500 之间时,显示正常。当字符读数变为 500 到 100 时,读数显示:

<span style="color: #55a500;">Characters remaining: 499</span>

那么如何让 JS 真正将 css 踢成正确的显示效果,而不是简单地在页面上回显??

如果相关,jQuery 正在使用中。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    或者只是为了好玩:您可能会喜欢这种更通用的 css/data-attributes 而没有 jquery 方法:

    [].slice.call(
      document.querySelectorAll('div[data-isRestrictedTextArea]')
    ).forEach(
      function(el) {
        var txtarea = el.querySelector('textarea')
           ,cntr = el.querySelector('div[data-iscounter]');
        
        cntr.setAttribute('data-maxlen', el.getAttribute('data-maxlen'));
        txtarea.onkeyup = count;
      }  
    );
    
    function count(e) {
      var len  = this.value.length,
          cntr = this.parentNode.querySelector('div[data-iscounter]'),
          maxl = this.parentNode.getAttribute('data-maxlen'),
          warn = maxl-Math.floor(0.2*maxl), // 80%  
          stop = maxl-Math.floor(0.1*maxl); // 90%
    
      cntr.setAttribute('data-ncharacters', len);
      cntr.className = len >= stop ? 'stop'
                       : len >= warn ? 'warn' 
                       : '';
      // truncate if len>=maxlen
      this.value = len >= maxl ? this.value.substr(0, maxl) : this.value;
      // set attribute for reporting
      cntr.setAttribute('data-ncharacters', len >= maxl ? maxl : len);
      return;
    }
    body {font: 12px/15px normal verdana,arial;}
    
    div[data-isrestrictedTextarea] {
      display: inline-block;
      margin-top: 1em;
    }
    
    div[data-iscounter] {
      color: green;
      background-color: #eee;
    }
    
    div[data-iscounter]:before {
      content: 'you typed 'attr(data-ncharacters)' characters';
    }
    
    div[data-iscounter]:after {
        content: ' [max 'attr(data-maxlen)' characters]';
    }
    
    div[data-iscounter].warn {
      color: orange;
    }
    
    div[data-iscounter].stop {
      color: red;
    }
    <div data-isrestrictedTextarea="1" data-maxlen="15">
      <textarea placeholder="start typing" rows="2" cols="60"></textarea>
      <div id="cnt_cnttxt" data-iscounter="1" data-ncharacters="0"></div>
    </div>
    
    <div data-isrestrictedTextarea="1" data-maxlen="100">
      <textarea placeholder="start typing" rows="5" cols="60"></textarea>
      <div id="cnt_cnttxt" data-iscounter="1" data-ncharacters="0"></div>
    </div>

    【讨论】:

      【解决方案2】:

      由于您使用的是 HTML 标记,因此无法使用 .text() 方法设置它们。请改用.html() 方法:

      我添加了一些清理代码。将计算设置在一个变量中以使其更清晰...

      $(window).load(function() {
          $("#input_4_1").keyup(function() {
              var diff = (2550 - $(this).val().length);
              if (diff >= 501) {
                  $("#count_4_1").html("Characters remaining: " + diff);
              } else if ((diff <= 500) && (diff >= 101)) {
                  $("#count_4_1").html("<span style=\"color: #55a500;\">Characters remaining: " + diff + "</span>");
              } else if (diff <= 100) {
                  $("#count_4_1").html("<span style=\"color: #ff0000;\">Characters remaining: " + diff + "</span>");
              }
          });
      });
      

      【讨论】:

      • 谢谢你,LcSalazar,你的解释和整理的代码已经很好地解决了我的问题。非常感激。感谢其他所有回答的人 - 没有错误的答案,但遗憾的是我只能将一个标记为已接受的答案。我标记了最适合我正在做的事情,并帮助整理了正在做的代码。不过现在还有一个问题,我会在另一篇文章中问这个问题!
      【解决方案3】:

      有很多方法可以做到:

      首先在您的 HTML 中创建一个标记为:

      <div id="warning"></div> /* Exactly above or below your text box */
      

      接下来在你的 JS 中你可以使用:

      Javascript:

      var html= "<span style='color: #55a500;'>Characters remaining: 499</span>";
      document.getElementById("warning").innerHtml(html);
      

      使用 Jquery:

      var html= "<span style='color: #55a500;'>Characters remaining: 499</span>";
      document.getElementById("warning").innerHtml(html);
      $('#warning').html(html);
      

      $(window).load(function() {
          $("#input_4_1").keyup(function() {
              if (2550 - $(this).val().length >= 501) {
                  $("#count_4_1").html("Characters remaining: " + (2550 - $(this).val().length));
              } else if ((2550 - $(this).val().length <= 500) && (2550 - $(this).val().length >= 101)) {
                  $("#count_4_1").html("<span style=\"color: #55a500;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
              } else if (2550 - $(this).val().length <= 100) {
                  $("#count_4_1").html("<span style=\"color: #ff0000;\">Characters remaining: " + (2550 - $(this).val().length) + "</span>");
              }
          });
      });
      

      【讨论】:

        【解决方案4】:

        来自 jQuery 页面,关于 .text(这里:http://api.jquery.com/text/):

        我们需要注意,此方法会根据需要对提供的字符串进行转义,以便在 HTML 中正确呈现。为此,它调用 DOM 方法 .createTextNode(),不会将字符串解释为 HTML

        (强调我的。)

        您需要使用.append 函数(此处为http://api.jquery.com/append/)将文本附加到页面,而不是将其与.text 一起放置。

        此外,如果要放置新字符串的元素中没有其他内容,您可以简单地使用 .html(此处为:http://api.jquery.com/html/)将容器的全部内容替换为新字符串。

        【讨论】:

        • @Pointy 是的,谢谢。在重新检查代码以查看它是否看起来像 .html 可能工作后,已经在编辑以添加它。
        猜你喜欢
        • 2016-01-08
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 2014-10-26
        • 2012-01-02
        • 1970-01-01
        • 2017-11-27
        相关资源
        最近更新 更多