chrome下判断点击input上标签还是其余标签

想要实现的功能:当input框失焦且点击的不是清除键时,执行reset方法重置input样式,当点击清除键时,执行clear方法,清除input内容。如图

本想通过如下代码来实现

    $(".search-input").focusout(function () {
                    if (document.activeElement.className !== 'close-t') {//close-t为清除键类名
                        $('.search-input').addClass('search-before');
                        $('.close').css('display', 'none');
                       
                        document.getElementById('search').value = '';
                    }
                });
以外的发现,当inpu框失焦后,首先获得焦点的,竟是body标签,也因为这样,该方法失效了,最后采用以下代码来实现的该功能
  $("#search").focusout(function () {
                   //判断失焦后是否点击的是清除钮,若是则不重置
                    var tapCloseButton = false;
                    $('.close-t').focus(function () {
                        tapCloseButton = true;
                    });
                    setTimeout(function () {
                        if (!tapCloseButton) {
                            $('.search-input').addClass('search-before');
                            $('.close').css('display', 'none');
                            document.getElementById('search').value = '';
                        }
                    },10);
                });
将焦点判断这一步骤延迟执行,故此时焦点已经从body上移到了真正所点击的元素上,此时再对焦点进行判断,看是否为清除键。
发布了109 篇原创文章 · 获赞 11 · 访问量 23万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章