Keep <div> and its children in focus until focus out of <div>

匿名 (未验证) 提交于 2019-12-03 08:56:10

问题:

I've seen similar topics posted on SO but mine is slightly different. I'm trying to keep my parent DIV (and children) in focus until I focus out of the div, and it seems surprisingly hard to accomplish.

This solution I thought would work but it looks to only applies to sibling elements and not the actual div itself.

Here's a demo of what I'm trying to do http://jsfiddle.net/nosfan1019/9Eg3k/3/. I need it so you can click on the gray portion and not have it disappear.

回答1:

Okay, I think that this is what you want:

Demo: http://jsfiddle.net/SO_AMK/GNfzw/

HTML:

<div>     <input type='text'>     <span></span> </div>  <div>     <input type='text'>     <span></span> </div>  <div>     <input type='text'>     <span></span> </div>

CSS:

div {     margin: 20px;     padding: 10px;     outline: 0; }

jQuery:

$(function() {     $('div input').parent().attr("tabindex",-1).focus( function() {         $(this).css('background','#eee');         $(this).find('span').text(' triggered');          $(this).focusout(function() {             $(this).children('span').empty();             $(this).css('background','white');          });                 });     $('div input').focus( function() {         $(this).parent().css('background','#eee');         $(this).siblings('span').text(' triggered');          $(this).parent().focusout(function() {             $(this).children('span').empty();             $(this).css('background','white');          });                 });  });

It could probably be more efficient but it seems to work.



回答2:

This is a bit of a more literal approach than the other answer, but for completeness seems relevant as it does one more thing: Autofocus back to the input. It could be useful, although the other answer is probably easy enough.

$(function() {     var $divs = $('div'),         $entered = null;      var on = function() {         var $target = $(this);          _off();          $entered = $target.parent().addClass('on');         $target.siblings('span').text(' triggered');     };      var focus = function(){         $(this).find('input').focus();     };      var off = function() {         if ($entered !== null && $(this).parent().is($entered)) {             return;         }          _off();     };      var _off = function(){         $divs.removeClass('on').children('span').text('');     };      var entered = function(e){         if (e.type == 'mouseenter') {             $entered = $(this);         } else {             $entered = null;         }     };      $divs.find('input').focus(on).blur(off);      $divs         .attr('tabindex', -1)         .bind('mouseenter mouseleave', entered)         .bind('focus', focus); });

http://jsfiddle.net/userdude/34HLU/2/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!