jQuery 推特上的人物倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2136647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:50:54  来源:igfitidea点击:

Character countdown like on twitter

jquerytwitter

提问by argon

How can I make a "remaining characters" countdown like the one on Twitter with jQuery? And also limit the input to a textarea.

如何使用 jQuery 像 Twitter 上的那样进行“剩余字符”倒计时?并且还将输入限制为文本区域。

回答by Brian McKenna

Make a spanand textareaand give them unique selectors (using an ID or class) like so:

制作一个spanandtextarea并为它们提供唯一的选择器(使用 ID 或类),如下所示:

<textarea class="message" rows="2" cols="30"></textarea>
<span class="countdown"></span>

And then make an update function like so:

然后像这样创建一个更新函数:

function updateCountdown() {
    // 140 is the max message length
    var remaining = 140 - jQuery('.message').val().length;
    jQuery('.countdown').text(remaining + ' characters remaining.');
}

And make that function run when the page is loaded and whenever the message is changed:

并在页面加载和消息更改时运行该函数:

jQuery(document).ready(function($) {
    updateCountdown();
    $('.message').change(updateCountdown);
    $('.message').keyup(updateCountdown);
});

Visit an exampleand view the source. jQuery makes things like this very simple.

访问示例查看源代码。jQuery 使这样的事情变得非常简单。

回答by Ryan McGeary

I've used Aaron Russell's simply countable jQuery pluginwith success; though, if I were to have written it, I would have designed it a bit differently (automatic counter div creation, using a data-maxlength attribute instead of a plugin option, etc).

我已经成功使用了 Aaron Russell 的简单可数的 jQuery 插件;不过,如果我要写它,我会设计它有点不同(自动计数器 div 创建,使用 data-maxlength 属性而不是插件选项等)。

Simple usage:

简单用法:

$('#my_textarea').simplyCountable();

Advanced usage:

高级用法:

$('#my_textarea').simplyCountable({
    counter: '#counter',
    countable: 'characters',
    maxCount: 140,
    strictMax: false,
    countDirection: 'down',
    safeClass: 'safe',
    overClass: 'over',
    thousandSeparator: ','
});

回答by Nikolay Ivanov

It's a suicide to use jQuery, Mootools or similar for such simple task ... unless you are already using them for something else.

使用 jQuery、Mootools 或类似工具来完成如此简单的任务是一种自杀……除非您已经将它们用于其他用途。

Simple javascript function:

简单的javascript函数:

function limitTextCount(limitField_id, limitCount_id, limitNum)
{
    var limitField = document.getElementById(limitField_id);
    var limitCount = document.getElementById(limitCount_id);
    var fieldLEN = limitField.value.length;

    if (fieldLEN > limitNum)
    {
        limitField.value = limitField.value.substring(0, limitNum);
    }
    else
    {
        limitCount.innerHTML = (limitNum - fieldLEN) + ' charachter(s) to go.';
    }
}

The first parameter is id of the input/textarea. The second - id of the div to display characters left. The third is the limit itself.

第一个参数是输入/文本区域的 id。第二个 - 显示剩余字符的 div id。第三是极限本身。

And simple HTML:

和简单的 HTML:

<input type="text" value="" name="title" id="title" maxlength="100" onkeyup="limitTextCount('title', 'divcount', 100);" onkeydown="limitTextCount('title', 'divcount', 100);">
<br>
<div id="divcount">100 charachter(s) to go..</div>

回答by chorbs

I added a simple pluralize function, cus nobody likes bad grammar.

我添加了一个简单的复数函数,因为没有人喜欢糟糕的语法。

function pluralize(count, word){
  if (count == 1 || count == -1){
    return String(count) + ' ' + word;
  }else{
    return String(count) + ' ' + word + 's';
  }
}

function updateCountdown() {
    // 140 is the max message length
    var remaining = 140 - jQuery('#micropost_content').val().length;
    jQuery('.countdown').text(pluralize(remaining,'character') + ' remaining');
}

...

回答by Mat Schaffer

We ended up doing a custom JS solution that operates on any input with class "limited". It uses an HTML5 custom data attribute ("data-maxlength") to specify the length. Of course, this is not nearly as full-featured as the plugin Ryan mentioned. But we needed multiple, dynamically added counters which didn't seem to be supported by the plugin. Hope that helps.

我们最终做了一个自定义的 JS 解决方案,该解决方案可以对类“有限”的任何输入进行操作。它使用 HTML5 自定义数据属性(“data-maxlength”)来指定长度。当然,这并不像 Ryan 提到的插件那样功能齐全。但是我们需要多个动态添加的计数器,插件似乎不支持这些计数器。希望有帮助。

function addCharacterCount(input) {
  var $input    = $(input),                                                                     
      maxLength = $input.data('maxlength'),
      remaining = maxLength - $input.val().length;                                              
  $('<label><input type="text" id="' + input.id + '-counter" size="3" value="' + remaining + '" /> Characters remaining (max ' + maxLength + ')</label>').insertAfter(input);
}

$('form .limited').each(function () {                                                           
  addCharacterCount(this);                                                                      
}); 

$('form .limited').live('keyup', function() {                                                   
  var $element = $(this),
      maxLength = $element.data('maxlength');
  $("#" + this.id + "-counter").val(maxLength - $element.val().length);
});

回答by Rikin Patel

I Updated @Brian McKenna version for multiple textarea/textbox with maxlegth attribute.

我更新了 @Brian McKenna 版本的多个 textarea/textbox 与 maxlegth 属性。

Demo here

演示在这里

<textarea class="message" rows="2" cols="30" maxlength="60"></textarea>
<span class="countdown"></span>

<textarea class="message" rows="2" cols="30"  maxlength="100"></textarea>
<span class="countdown"></span>

On page load update all count.

在页面加载更新所有计数。

jQuery(document).ready(function($) {
    updateCountdownAll();
    $('.message').live('input', updateCountdown);

});

Make two function for update count.

为更新计数制作两个函数。

function updateCountdownAll() {
        $('.message').each(function () {
            updateCountdown(this);
        });
    }

    function updateCountdown(e) {

        var currentElement;
        if (e.target) {
            currentElement = e.target;
        }
        else {
            currentElement = e;
        }

        var maxLengh = $(currentElement).attr('maxlength');
        var remaining = maxLengh - $(currentElement).val().length;
        $(currentElement).nextAll('.countdown:first').text(remaining + ' character(s) remaining.');
    }

回答by Brian Edwards

In my implementation, I added the following JS function:

在我的实现中,我添加了以下 JS 函数:

function charactersRemaining(elementID, messageElementID, maxCharacters)
{
    var remaining = maxCharacters - $('#' + elementID).val().length;
    $('#' + messageElementID).text(remaining + ' characters remaining.');
}

Then I could reuse that function all over the application (for example, if I had the following HTML):

然后我可以在整个应用程序中重用该函数(例如,如果我有以下 HTML):

<textarea class="form-control" asp-for="Comments" rows="3"></textarea>
<span id="commentsCharsRemaining" class="text-primary"></span>

Just add these 2 jquery statements to make it work:

只需添加这 2 个 jquery 语句即可使其工作:

$('#Comments').change(function () {
    charactersRemaining('Comments', 'commentsCharsRemaining', 2000)
});
$('#Comments').keyup(function () {
    charactersRemaining('Comments', 'commentsCharsRemaining', 2000)
});

回答by Rhonda Te Moananui

HTML:

HTML:

<form>
    <!-- remember to markup your forms properly using labels! -->
    <label for="textareaChars">No more than 100 characters</label>

    <textarea id="textareaChars" maxlength="100"></textarea>

    <p><span id="chars">100</span> characters remaining</p>

</form>

JS:

JS:

$( document ).ready(function() {
    var maxLength = 100;
    $('textarea').keyup(function() {
        var length = $(this).val().length;
        var length = maxLength-length;
        $('#chars').text(length);
    });
});

回答by Sujay sreedhar

use jquery

使用jQuery

save this as jquery.textlimiter.js

将此保存为 jquery.textlimiter.js

(function($) {
    $.fn.extend( {
        limiter: function(limit, elem) {
            $(this).on("keyup focus", function() {
                setCount(this, elem);
            });
            function setCount(src, elem) {
                var chars = src.value.length;
                if (chars > limit) {
                    src.value = src.value.substr(0, limit);
                    chars = limit;
                }
                elem.html( limit - chars );
            }
            setCount($(this)[0], elem);
        }
    });
})(jQuery);

usage

用法

<textarea id="text" maxlength="100" cols="50" rows="5" placeholder="Enter Text"></textarea>
    <div id="chars">100</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="path/to/jquery.textlimiter.js"></script>
<script>
$(document).ready( function() {
    var elem = $("#chars");
    $("#text").limiter(100, elem);
});
</script>