我有一个"发布"按钮,当文本输入文本时,它会激活(从模糊到颜色,从禁用到启用)。
这工作正常,但我希望文本区域在文本区域中没有任何内容时检测到。所以假设我在文本区域中输入了"abc"。提交按钮将变为活动状态,但假设我现在删除了所有文本。按钮仍处于活动状态。好吧,不完全,因为我有这个:
commentButton.prop({ disabled: commentBox.val() == 0 });
这将阻止表单提交,文本区域中没有任何内容。问题是提交按钮仍然是彩色的,并且不会像预期的那样返回到模糊的非活动状态。
所以这让我想到了我的问题。
我可以设置一些东西,一旦我专注于文本区域并键入并知道何时从文本区域删除了所有内容,就会激活并开始收听吗?
这样,我可以设置一个 if 语句来说明文本是否全部删除,然后删除彩色状态按钮的 moveClass 和模糊状态按钮的 addClass。
这也应该适用于空格。
这是我当前的代码:
.comment_box = 我的文本区域
.activeCommentButton = 彩色提交按钮
.commentButton = 模糊的提交按钮
$(".microposts").off().on("focus", ".comment_box", function () {
$(this).prop("rows", 7);
$(this).parent().find(".activeCommentButton").removeClass("activeCommentButton").addClass("commentButton");
var commentBox = $(this),
form = $(this).parent(),
cancelButton = form.children(".commentButtons").children(".cancelButton"),
commentButton = form.children(".commentButtons").children(".commentButton");
$(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();
form.children(".commentButtons").addClass("displayButtons");
commentButton.prop({
disabled: true
});
commentBox.off().on("keyup keypress input change", function () {
commentButton.prop({
disabled: commentBox.val() == 0
});
commentButton.removeClass("commentButton").addClass("activeCommentButton");
});
cancelButton.click(function () {
commentBox.removeClass("comment_box_focused").addClass("comment_box");
form.children(".commentButtons").removeClass("displayButtons");
commentBox.val("");
});
});
亲切问候
是的,试试这个,你可以修改它:
$(".commentButton").prop({ disabled: true });
$(".comment_box").keypress(function() {
$(".commentButton").prop({ disabled: !$(this).val().length >= 1 })
});
这对我有用,但有没有更清洁的方法?
commentButton.prop({ disabled: true });
commentBox.off().on("keyup keypress input change", function () {
commentButton.prop({ disabled: commentBox.val().length == 0 });
if ( commentBox.val().length > 1 ) {
commentButton.removeClass("commentButton").addClass("activeCommentButton");
} else {
commentButton.removeClass("activeCommentButton").addClass("commentButton");
}
});