我有一个textarea和一个按钮。当我单击按钮时,我想在textarea中插入文本。但是,我插入的文本取决于texteara的当前焦点。以下是一些案例:
(截至点击按钮时)
这是我的示例实现的小提琴: https://jsfiddle.net/reL9ro6L/1/
$(document).ready(function() {
$('button').click(function() {
var $text = $('textarea');
var currentValue = $text.val(),
len = currentValue.length,
isTextAreaFocused = $text.is(':focus'),
optionalNewline = isTextAreaFocused ? '' : '\n';
var start = $text[0].selectionStart,
end = $text[0].selectionEnd,
beforeText = isTextAreaFocused ? currentValue.substring(0, start) : len,
afterText = isTextAreaFocused ? currentValue.substring(end) : len;
var insertedText = 'foo',
newValue = beforeText + insertedText + afterText + optionalNewline;
$text.val(newValue);
});
})
我相信按钮会在它有机会知道textarea是否聚焦之前聚焦。是否有一个钩子或方法来处理按钮上的点击事件,以便我知道(在它聚焦之前)什么是焦点?
关闭点:我使用Ember作为我的框架。我真的很想看到一个纯粹的JS / jQuery解决方案,但我只想把Ember放在桌面上。
答案 0 :(得分:2)
你必须在按钮上使用mousedown
事件,因为它会在textarea失去焦点之前触发。
当click
事件触发时,鼠标已被按下并释放,焦点将转移到该按钮。
$(document).ready(function() {
$('button').on({
mousedown: function() {
var text = $('textarea').get(0),
currentValue = text.value,
isTextAreaFocused = text === document.activeElement,
insertedText = 'foo',
start = text.selectionStart,
end = text.selectionEnd,
beforeText = currentValue.substring(0, start) || "",
afterText = currentValue.substring(end) || "",
newValue = beforeText + insertedText + afterText;
text.value = isTextAreaFocused ? newValue : currentValue + insertedText + '\n';
$(this).data({'focus' : isTextAreaFocused, 'end' : end + insertedText.length});
},
mouseup: function() {
if ( $(this).data('focus') ) {
$('textarea').focus().get(0).setSelectionRange($(this).data('end'), $(this).data('end'));
}
}
});
});
textarea {
width: 20em;
height: 10em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<button>Insert text</button>