[英]How can I hide a <div> and have it show only when a <textarea> has focus?
[英]How do I show a div when a textarea is focused and hide it when the textarea is blurred in jQuery?
所以我的问题要复杂一些,然后我才能填写标题。 我正在尝试重新创建类似trello如何在卡片上发表评论的内容。 在trello上,当您在新评论文本区域内单击时,该文本区域将展开,并显示一个div,其中包含“提交评论”链接以及用于其他操作的其他一些链接(请将该div称为“ links-div”。
他们只是通过在“ links-div”的父div中添加“以焦点为重点”的类来完成此操作,并通过CSS处理取消隐藏。
我被卡住的地方是,如果您在文本区域之外单击(使其模糊),则文本区域会缩小,并且除非您单击“ links-div”内部的链接之一,否则“ links-div”会再次隐藏。
我想重新创建它,并且能够在我的“ links-div”内单击链接或提交按钮而不会隐藏它,但是,如果我单击该“ links-div”之外的任何内容,它应该照常隐藏。 我将如何重新创建它? 谢谢。
这是一个潜在的解决方案jsbin
通过监视.comment
内元素的focus
和blur
事件,以及在.comment
本身上切换类来工作。
当.comment
内部的元素上发生blur
事件时,我们可以使用e.relatedTarget
来找出哪个元素具有新的焦点。 然后我们可以检查新关注的元素是否在.comment
内部。 如果是这样,我们“取消” blur
。 如果没有,我们照常继续。
HTML
<div class="comment">
<textarea id="ta"></textarea>
<div class="controls">
<button>One</button>
<a href="#">Two</a>
</div>
</div>
<div>
<a href="#">This is outside the comment</a>
</div>
CSS
.comment .controls {
display: none;
}
.comment.is-focused .controls {
display: block;
}
Javascript / jQuery
// The selector ".comment *" will grab any element INSIDE a .comment
$('.comment *').on('focus', function () {
// Whenever an element inside a comment gets the focus, give
// its parent element a class
$(this).parents('.comment').addClass('is-focused');
});
$('.comment *').on('blur', function (e) {
var $newFocus = $(e.relatedTarget);
if ($newFocus.parents('.comment').length > 0) {
// The newly focused element is inside a comment (potentially
// not the SAME comment - you'll want to fix this) so cancel
// the blur
e.preventDefault();
return;
}
// The newly focused element is outside a comment, so continue
// to blur this element and also remove our class
$(this).parents('.comment').removeClass('is-focused');
});
因此,在仔细阅读@Alex McMillan的回答后,我开始了这项工作。 实际上,这比我想的要简单。 我没有在文本区域上使用.on 'focus'
和.on 'blur'
事件,而是在文档上使用了.on 'mousedown'
事件。
这是一个jsfiddle https://jsfiddle.net/h9ohkzdf/8/ 。
我可能会尝试并使用一个包含div而不是整个文档,看看是否可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.