2016-12-25 60 views
2

我有这个非常简单的点击事件,如果input已被集中,它应该添加一个类到所述input输入时没有添加班级时重点

但是,它不想添加类。我一直确定包括jQuery库,但没有任何反应。

jQuery的

$("body").on("click", function(){ 
    if($("input").is(":focus")){ 
     $(this).addClass("highlight-input"); 
    } else { 
     $(this).removeClass("highlight-input"); 
    } 
}); 
+0

你为什么想检查是否所有的输入你的网页是专注于?只有一个元素可以有焦点。这将**总是**为假。 –

+0

而不是jQuery使用CSS':focus' – Tushar

+0

@Tushar焦点和悬停是完全不同的...... –

回答

2

你需要用这样的方式:

$(document).ready(function() { 
    $("input").on("focus", function() { 
    $(this).addClass("highlight-input"); 
    }).on("blur", function() { 
    $(this).removeClass("highlight-input"); 
    }); 
}); 
+1

已经尝试过这个,但我会再次尝试与您的代码..一刻 –

+0

@Celan。不要忘了'$(document).ready(function(){'... –

+0

哈哈耶,犯了太多错误 –

2

在你的代码 - this表示body元素,所以当你使用$(this).addClass("highlight-input");highlight-input类添加到body元素。

$("body").on("click", function(){ 
 
    if($("input").is(":focus")){ 
 
     debugger; 
 
     $(this).addClass("highlight-input"); 
 
    } else { 
 
     $(this).removeClass("highlight-input"); 
 
    } 
 
});
.highlight-input { 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input />

这很可能是你在找什么:

$('input').on('focus', function() { 
 
    $(this).addClass("highlight-input"); 
 
}).on('blur', function() { 
 
    $(this).removeClass("highlight-input"); 
 
});
.highlight-input { 
 
    background: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input />

+0

将课程添加到身体! :( –

+0

正确,我说它有效,但我不确定这是他看的东西:)仔细阅读。 – Dekel

+0

我仔细阅读:'它应该添加一个类,以说输入.' –