这里我有一个小提琴Fiddle。
我想要的是将#searchbox
相应地放在textarea上输入的关键字旁边。但是我如何在textarea中获得输入关键字的位置并定位#searchbox
?
答案 0 :(得分:0)
这就是我现在所拥有的。
我一直试图让它工作一个小时,但我现在必须回到自己的工作。
This is what i have got so far
也许你或某个想要的人可以使用它,也许它可以解决!
我想听听你做了什么,当你最终成功的时候!
Good luck!
答案 1 :(得分:0)
以下是我尝试的内容:
<强> DEMO 强>
首先,使用带有textarea
属性的div
代替contenteditable
,我们可以在div
内输入文字并放置元素。
接下来,jQuery:
var lines = 1;
var first_line = true;
//Credits to digitalzoomstudio at http://digitalzoomstudio.net/2013/06/19/calculate-text-width-with-jquery/
//This function finds the exact width of the text entered
jQuery.fn.textWidth = function () {
var _t = jQuery(this);
var html_org = _t.html();
if (_t[0].nodeName == 'INPUT') {
html_org = _t.val();
}
var html_calcS = '<span>' + html_org + '</span>';
jQuery('body').append(html_calcS);
var _lastspan = jQuery('span').last();
_lastspan.css({
'font-size': _t.css('font-size'),
'font-family': _t.css('font-family')
})
var width = _lastspan.width() + 5;
_lastspan.remove();
return width;
};
$("#textarea").one("keyup", function () {
//the searchbox should show only the first time the key is pressed
$('#searchbox').show();
});
$('#textarea').keyup(function (e) {
if(first_letter = true){
$('#searchbox').show();
}
if (first_line) {
//Credits to Viral Patel for this bit of code at http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
//This one retrieves the text instead a div after removing
//all its child elements
var content = $(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
$('#searchbox').css('top', 20);
} else {
var content = $('div', this).eq(-2).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
}
lastLine = "<span>" + content + "</span>";
pos = $(lastLine).textWidth();
$('#searchbox').css('top', lines * 20);
$('#searchbox').html(content);
if (e.keyCode == 13) {
first_line = false;
lines = lines + 1;
$('#searchbox').css('left', 20);
$('#searchbox').html('');
$('#searchbox').hide();
first_letter = true;
} else {
$('#searchbox').css('left', pos + 10);
first_letter = false;
}
});