最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add andor Remove Class from a form Element using jQuery - Stack Overflow

programmeradmin0浏览0评论

I need a jQuery script that will add a class when the user is focused on the form element and when the user leaves the form element, the class is removed.

$("#search_text").click(function() {
    $(this).removeClass('search').addClass('search_active');
    $('#search_icon').removeClass('search_icon').addClass('search_icon_active');
});

This script adds the class, but does not remove it when the user has the left the element.

I need a jQuery script that will add a class when the user is focused on the form element and when the user leaves the form element, the class is removed.

$("#search_text").click(function() {
    $(this).removeClass('search').addClass('search_active');
    $('#search_icon').removeClass('search_icon').addClass('search_icon_active');
});

This script adds the class, but does not remove it when the user has the left the element.

Share Improve this question edited Nov 14, 2018 at 14:44 dustbuster 82.2k7 gold badges26 silver badges43 bronze badges asked Sep 5, 2011 at 19:11 ViktorsViktors 9353 gold badges13 silver badges33 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

As said by Daniel A. White, you should use .focus and .blur

$("#search_text").focus(function() {
    $(this).removeClass('search').addClass('search_active');
    $('#search_icon').removeClass('search_icon').addClass('search_icon_active');
});

$("#search_text").blur(function() {
    $(this).removeClass('search_active').addClass('search');
    $('#search_icon').removeClass('search_icon_active').addClass('search_icon');
});

For more information on: Focus: http://api.jquery./focus/ Blur: http://api.jquery./blur/

Have a look at the .focus and .blur jquery events.

If you don't mind excluding IE 6 and 7 you can use the :focus CSS event.

input { background-color: #F7F7F7; }
input:focus { background-color: #FFFFFF; }
发布评论

评论列表(0)

  1. 暂无评论