我搜索了很多,但没有找到令人满意的结果, 我正在尝试使用 JavaScript 为我的自动完成文本框获取文本正下方的 div
<input type="text" id="one" onkeyup="suggest(event,this)" />
<p>
<input type="text" id="two" onkeyup="suggest(event,this)" />
<p>
<input type="text" id="two" onkeyup="suggest(event,this)" />
javascript:
function suggest(e,the)
{
//here i want to create a div and place just below the textbox on which the keyispressed
}
any help!
最佳答案
一般来说,将 javascript 事件附加到 html 中并不是一个好主意。我的想法是动态创建一个 div 并将其定位在输入字段的正下方我认为以下代码将起作用。这也是一个 jsfiddle http://jsfiddle.net/krasimir/qCXPu/3/
<div class="wrapper">
<input type="text" id="one" class="suggest" />
<p>some text</p>
<input type="text" id="two" class="suggest" />
<p>some text</p>
<input type="text" id="three" class="suggest" />
</div>
JavaScript:
var inputs = document.querySelectorAll('.suggest');
for(var i=0; field=inputs[i]; i++) {
field.addEventListener('keyup', function(event) {
var text = 'You typed: ' + this.value;
if(!this.suggestion) {
var rect = this.getBoundingClientRect();
var left = rect.left;
var top = rect.bottom;
this.suggestion = document.createElement('DIV');
this.suggestion.innerHTML = text;
this.suggestion.setAttribute('style', 'background: #B0B0B0; padding: 6px; position: absolute; top: ' + top + 'px; left: ' + left + 'px;');
this.parentNode.appendChild(this.suggestion);
} else {
this.suggestion.innerHTML = text;
this.suggestion.style.display = 'block';
}
});
field.addEventListener('blur', function(event) {
if(this.suggestion) {
this.suggestion.style.display = 'none';
}
});
}
关于javascript - 在文本框下方放置一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18442836/