JQuery:当表单聚焦或对话被鼠标悬停时,防止fadeOut

时间:2009-07-21 10:57:41

标签: jquery user-interface forms

标题有点模糊,但我无法在字符限制中解释它。

我正在创建一个小屏幕,当您将鼠标悬停在某些触发链接上时会出现对话框。其中两个包含表单(登录提示和注册表单)。目前,如果您将鼠标悬停在链接或对话框本身上,它们将保持100%不透明度,并且在鼠标移动时它们会逐渐消失。如果表单输入被聚焦,我一直在尝试阻止mouseout淡出,但如果没有输入聚焦,请保留它。

因为不可能做像

这样的事情

var input = $(input); if (input.is(':focused'){ //do something };

我目前正在使用的代码并没有按照我想要的方式运行:

// Fade the login box.
$(document).ready(function() {
var hide = false;
    var formfocus = false;
// If the link or the dialogue is hovered
$(".log1, .login").hover(function(){
    //Clear the hide timeout
    if (hide) clearTimeout(hide);
    // Fade out the other dialogues
    $(".register, .about").fadeOut(40);
    // Fade in the login dialogue
    $(".login").fadeIn();
}, function() {
    // If an input gains focus, set the variable to true
    $('input').focus(function(){
    if (hide) clearTimeout(hide);
    var formfocus = true;
    });
    // If an input loses focus, set the variable to false
    $('input').blur(function(){
        var formfocus = false;
    });
    // Self explainatory
    if (formfocus==false){
        hide = setTimeout(function() {$(".login").fadeOut();}, 400);
    }
});
});

尽管上述内容具有逻辑意义(至少对我而言),但它并不像我预期的那样有效。如果有人知道如何实现这一点,我很乐意听到它。

谢谢, 布伦丹。

2 个答案:

答案 0 :(得分:0)

我只是遵循你的逻辑并简化以下内容:

$(function() {
        var hide = false;
        $(".trigger, .login").hover(function() {
            if (hide) clearTimeout(hide);
            $(".login").fadeIn(500);
            $(".login2").fadeOut(500);
        }, function() {
            // Make timeout for this
            hide = setTimeout(function() { $(".login").fadeOut(500); }, 1000);
        });

        $(".trigger2, .login2").hover(function() {
            if (hide) clearTimeout(hide);
            $(".login2").fadeIn(500);
            $(".login").fadeOut(500);
        }, function() {
            // Make timeout for this
            hide = setTimeout(function() { $(".login2").fadeOut(500); }, 1000);
        });
    });

各自的HTML是:

<div class="main">
    <div class="trigger">
        Trigger Login
    </div>
    <div class="trigger2">
        Trigger 2
    </div>
</div>
<div class="login">
    <input type="text" />
</div>
<div class="login2">
    <select>
        <option>FDKLFS</option>
    </select>
</div>

它在我的FF3.5中对我有用,唯一的主要区别是我没有考虑表单/ splash中的输入,我只是考虑将光标移出表单会触发超时。请注意,实现就像ad-hoc解决方案一样,它可以更好地重构一个更通用的函数调用来绑定所有这些事件。

答案 1 :(得分:0)

看起来你的代码逻辑不正确。 (请自己尝试,因为我现在无法验证它。)

由于您有以下声明:

 $('input').blur(function(){
            var formfocus = false;
 });

意味着 ANY 输入失焦,然后它会触发定时器开始倒计时。除非你只有 ONE 输入框用于启动,这当然保证定时器必须触发,考虑你的类型登录名,然后点击密码字段,然后你移动到其他窗口, hover_out是fire,计时器将启动!

你提到的是(:专注)你的问题,我认为可以自己实现这个,如果它有效,我认为它可以帮助你弄清楚路径。

Detect which form input has focus using JavaScript or jQuery