2011-12-15 60 views
0

我有一个javasccript功能,显示或隐藏“跨越”,当用户填写表单,当我点击输入显示的提示:注册一个点击,除了某一个元素

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事件并提示消失,所以我想知道如何修改此功能,以便它不会隐藏,当我点击暗示。

回答

1

您可以使用布尔型var来测试用户是否将鼠标悬停在您的提示上,然后如果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); 
} 

我把自我执行功能只是为了保持VAR i范围,你没有的onmouseout功能的麻烦。

编辑:更新的例子

您的得到下一个跨度将无法正常工作的代码,所以我改成nextElementSibling,因为你把例如在jsfiddler

+0

我把这个内循环,但跨度显示不出来人现在都,尝试了几种变化,但我真的很新的这一点,也许你能告诉我整个prepareInputsForHints()函数应该如何看起来像 – 2011-12-15 13:51:08

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); 
} 
});