我的页面上有大约1000个文本字段,需要在用户当前输入的文本字段上方显示工具提示。
听起来很简单,但我很难弄清楚如何在页面上的其他内容上显示它并且不会破坏文档的流量。
我也不能使用任何外部库,这使得它更难一点。我只允许使用纯JS(或编译为纯JS的语言,如TypeScript)。
有没有人有任何链接,教程或类似的东西?这将非常有帮助。
谢谢
编辑: 我知道你可以在一个元素上使用Title属性,但是这个工具提示需要的不仅仅是文本里面的文本,需要更大,直接在文本框上方。
答案 0 :(得分:3)
这样的事可能会对你有所帮助:
<div id="container">
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf" /><br />
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf2" /><br />
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf3" /><br />
<input type="text" class="tooltip" onfocus="theFocus(this);" onblur="theBlur(this);" title="asdf4" /><br />
<div id="tooltip"></div>
</div>
function theFocus(obj) {
var tooltip = document.getElementById("tooltip");
tooltip.innerHTML = obj.title;
tooltip.style.display = "block";
tooltip.style.top = obj.offsetTop - tooltip.offsetHeight + "px";
tooltip.style.left = obj.offsetLeft + "px";
}
function theBlur(obj) {
var tooltip = document.getElementById("tooltip");
tooltip.style.display = "none";
tooltip.style.top = "-9999px";
tooltip.style.left = "-9999px";
}
这显然非常狭隘,需要进行修改以完全符合您的需要。我没有用Javascript绑定focus
和blur
事件 - 这比将它们放在HTML中更好。
答案 1 :(得分:1)
您可以通过多种方式使用“CSS工具提示”。一个相对简单的想法是将提示内容放在最初用CSS隐藏的div
中,就在字段之前。然后,您需要一个onfocus
事件处理程序,将div
更改为可见(和onblur
处理程序,使其再次不可见)。您将拥有一个提示和字段的容器,并将该容器声明为相对位置,以便可以“绝对”(即相对于容器)定位提示。
示例(jsfiddle):
<!DOCTYPE HTML>
<meta charset=utf-8>
<style>
.textfield {
position: relative;
}
.textfield .hint {
display: none;
position: absolute;
width: 10em;
bottom: 1.3em;
background: #ff9;
padding: 0 0.2em;
border: solid 1px;
}
</style>
<script>
function hint(elem) {
elem.parentNode.firstElementChild.style.display = 'block';
}
function unhint(elem) {
elem.parentNode.firstElementChild.style.display = 'none';
}
</script>
<p>This is just some filler text.
<table>
<tr>
<td><label for=bar>Bar</label>
<td>
<div class=textfield>
<div class=hint>This is hint text for the Bar field.</div>
<input id=bar name=bar onfocus="hint(this)" onblur="unhint(this)">
</div>
<tr>
<td><label for=foo>Foo</label>
<td>
<div class=textfield>
<div class=hint>This is hint text for the Bar field.</div>
<input id=foo name=foo onfocus="hint(this)" onblur="unhint(this)">
</div>
</table>
(当使用表格来构建表单时,在这种方法中你需要记住CSS定位不适用于表格单元格。这就是为什么你不能使用td
元素作为包装但需要使用其中div
。)