我在 Rails 教程(第 10 章,练习 7)中尝试了 micropost 字符倒计时,使用此处的信息作为基础,并在此处和此处的 StackOverflow 答案的帮助下。
屏幕上是这样的,随着接近字数限制,文字逐渐变红,一旦微博超限,发帖按钮失效,就这样结束了。
当前的实现如下所示:
意见/共享/_micropost_form.html.haml
= form_for @micropost do |f|
= render 'shared/error_messages', object: f.object
.field= f.text_area :content, placeholder: t('.compose_micropost')
%span
.remaining= t('.characters_remaining').html_safe
.countdown
= f.submit t('.post'), class: "btn btn-large btn-primary"
资产/javascripts/microposts.js.coffee
updateCountdownAttributes = (toRemove, toAdd = null) ->
for attr in toRemove
$(".remaining, .countdown").removeClass attr
if toAdd
$(".remaining, .countdown").addClass toAdd
if toAdd is "overlimit"
$("input.btn.btn-large.btn-primary").attr("disabled", "true")
else
$("input.btn.btn-large.btn-primary").removeAttr("disabled")
updateCountdown = ->
remaining = 140 - $("#micropost_content").val().length
toRemove = ["nearlimit", "almostlimit", "overlimit"]
if remaining > 19
updateCountdownAttributes(toRemove)
if remaining < 20
toAdd = (toRemove.filter (attr) -> attr is "nearlimit").toString()
updateCountdownAttributes(toRemove, toAdd)
if remaining < 11
toAdd = (toRemove.filter (attr) -> attr is "almostlimit").toString()
updateCountdownAttributes(toRemove, toAdd)
if remaining < 0
toAdd = (toRemove.filter (attr) -> attr is "overlimit").toString()
updateCountdownAttributes(toRemove, toAdd)
$(".countdown").text remaining
$(document).ready ->
$(".countdown").text 140
$("#micropost_content").change updateCountdown
$("#micropost_content").keyup updateCountdown
$("#micropost_content").keydown updateCountdown
$("#micropost_content").keypress updateCountdown
资产/样式表/custom.css.scss
...
/* Micropost character countdown */
.remaining, .countdown {
display: inline;
color: $grayLight;
float: right;
}
.overlimit {
color: $red;
}
.almostlimit {
color: hsl(360, 57%, 21%);
}
.nearlimit {
color: $gray;
}
配置/语言环境/en.yml
en:
...
shared:
...
micropost_form:
compose_micropost: "Compose new micropost..."
post: "Post"
characters_remaining: " characters remaining."
从这里,我有两个问题/问题:
第一个是,如果可能的话,我希望能够对“剩余字符”字符串进行适当的复数。也许是这样的:
意见/共享/_micropost_form.html.haml
...
%span
.remaining= t('.characters_remaining', count: [[.countdown value]]).html_safe
.countdown
...
配置/语言环境/en.yml
...
micropost_form:
...
characters_remaining:
one: " character remaining."
other: " characters remaining."
但是,我不知道如何以.countdown
可以将其传递给count
参数的方式检索 div 中的值。我怎样才能做到这一点?
假设第一个问题可以解决,我也想去掉负数字符,而是将“-2 个字符剩余”更改为“2 个字符以上”。也许在视图中使用某种分支逻辑和一些 javascript 将负数更改为正数......?我不太确定这里,所以任何帮助将不胜感激。
意见/共享/_micropost_form.html.haml
...
%span
- [[ if .countdown value < 0 ]]
.remaining= t('.characters_over',
count: [[positive .countdown value]]).html_safe
- [[ else ]]
.remaining= t('.characters_remaining', count: [[.countdown value]]).html_safe
.countdown
...
配置/语言环境/en.yml
...
micropost_form:
...
characters_remaining:
one: " character remaining."
other: " characters remaining."
characters_over:
one: " character over."
other: " characters over."