0

我有一个 javascript 函数,当我单击输入以在用户填写表单时显示提示时显示或隐藏“spans”:

function prepareInputsForHints() {
var inputs = document.getElementsByTagName("input");

for (var i=0; i<inputs.length; i++){
    // test to see if the hint span exists first
    if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
        // the span exists!  on focus, show the hint
        inputs[i].onfocus = function () {
            this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
        }
        // when the cursor moves away from the field, hide the hint
        inputs[i].onblur = function () {
            this.parentNode.getElementsByTagName("span")[0].style.display = "none";
        }
    }
}
}

我的问题是,当我尝试向提示文本添加链接时,用户无法单击它,因为它首先注册了 onblur 事件并且提示消失了,所以我想知道如何修改此函数以使其不会单击提示时隐藏。

4

2 回答 2

1

您可以使用布尔变量来测试用户是否将鼠标悬停在您的提示上,然后如果 onblur 而不是 mouseOver 则隐藏您的提示。

在你的循环中是这样的:

var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){
    (function(i) {
        // Let the code cleaner :)
        var span = inputs[i].nextElementSibling;

        span.onmouseover = function() { this.isOver = true; }
        span.onmouseout = function() { this.isOver = false; if(!inputs[i].isFocus) inputs[i].onblur(); }

        // the span exists!  on focus, show the hint
        inputs[i].onfocus = function () {
            this.isFocus = true;
            span.style.display = "inline";
        }
        // when the cursor moves away from the field, hide the hint
        inputs[i].onblur = function () {
            this.isFocus = false;
            if(!span.isOver) span.style.display = "none";
        }
    })(i);
}

我放了一个自执行函数只是为了保持 vari范围,你没有麻烦 onmouseout 函数。

编辑:更新了示例

您获取下一个跨度的代码将不起作用,因此我更改为 nextElementSibling,因为您放入jsfiddler的示例。

于 2011-12-15T13:23:20.217 回答
0

这是新的工作代码:

$(function(prepareInputsForHints) {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){
    (function(i) {
        // Let the code cleane
        var span = inputs[i].nextElementSibling;

    if(span instanceof HTMLSpanElement) {

if(span.className == "hint") {


        span.onmouseover = function() { this.isOver = true; }
        span.onmouseout = function() { this.isOver = false; if(!inputs[i].isFocus) inputs[i].onblur(); }

        // the span exists!  on focus, show the hint
        inputs[i].onfocus = function () {
            this.isFocus = true;
            span.style.display = "inline";
        }
        // when the cursor moves away from the field, hide the hint
        inputs[i].onblur = function () {
            this.isFocus = false;
            if(!span.isOver) span.style.display = "none";
        }
}       
    }
    })(i);
}
});
于 2011-12-21T16:53:52.523 回答