2012-10-30 160 views
1

我正在使用jquery 1.8.2,有2個輸入字段,並想要一種方式來檢測每個人是否有焦點,或者都沒有焦點。在jQuery的焦點上,檢測焦點轉移或沒有元素有焦點

任何幫助將不勝感激,謝謝。

編輯:

我已經更新了的jsfiddle更接近我想要什麼,所以沒有混亂。這裏的問題是我有2個輸入字段綁在一起。當一個人聚焦時,我想成長一個,縮小另一個,並且如果兩個都不重點,我想重新設置它們的原始寬度。我可能會受到一些全局變量的影響,這些變量會更新焦點並記錄兩者是處於焦點還是焦點之外,但我想先看看是否存在jquery解決方案。這裏是更新的jsfiddle用按鈕切換復位動畫所以你可以看到它是如何跳的那一刻:

http://jsfiddle.net/LZn85/12/

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> 


<input class="searchy-search input1" /> 
<input class="searchy-search input2" /> 
<p>who has focus?</p> 
<div class="focus-who jquery-focus"></div> 

<button class="out-focus">toggle focus out</button>​ 

$(document).ready(function() { 
    $('.focus-who').html('init'); 
    $('.input1').val('some long string of text'); 
    $('.input2').val('some long string of text'); 

    $('.searchy-search').focusin(function() { 
     var $shrinkSelector; 
     if($(this).hasClass('input1')) { 
      $shrinkSelector = $('.input2'); 
     } else if($(this).hasClass('input2')) { 
      $shrinkSelector = $('.input1'); 
     } 
     var initWidth = 100; 
     var inputVal = $(this).val(); 
     var inputLength = inputVal.length; 

     if(inputLength > 16) { 
      var offset = ((inputLength - 16) * 6); 
      var growWidth = initWidth + offset; 
      var shrinkWidth = initWidth - offset; 
      var aniTime = 200; 
      $(this).animate({width: growWidth + 'px'}, aniTime); 
      $shrinkSelector.animate({width: shrinkWidth + 'px'}, aniTime); 
     } 
    }); 
    var outFocus = false; 
    $('.out-focus').click(function() { 
     outFocus = !outFocus; 
    }); 
    $('.searchy-search').focusout(function() { 
     if(outFocus) { 
      $('.searchy-search').animate({width: '130px'}, 200); 
     } 
    }); 
});​ 

另一個編輯:

看起來這可能只是我最好的選擇。如果任何人有任何其他想法會很棒,但現在我認爲我只需要去解決這個問題。

Detect which form input has focus using JavaScript or jQuery

回答

1

我不認爲這將與focusOut事件工作,因爲該事件的內容事件的焦點事件之前發生。所以你的代碼在瀏覽器知道現在有什麼焦點之前就開始了。爲什麼要檢查聚焦事件是否有原因?你可以做一些事情,同時使用的重點和focusOut事件:

$(document).ready(function() { 
    $('.focus-who').html('init'); 

    $('.searchy-search').focus(function() { 
     $('.jquery-focus').html($(this).attr("id")); 
    }); 

    $('.searchy-search').focusout(function() { 
     $('.jquery-focus').html("nothin"); 
    }); 
});​ 
+0

原因是我正在增加每個輸入焦點和縮小對方,因爲他們是捆綁的。我更新了我的jsfiddle以運行這些動畫,以及一個按鈕以切換焦點重置行爲,以便您瞭解從一個輸入移動到下一個時如何跳躍:http://jsfiddle.net/LZn85/12/ – brainTrain

1

這不是太清楚你希望做什麼,但是這可能幫助。

您可以檢測焦點是否已經從父元素parentEl的所有兒童搬走:

// Trigger when any children have lost focus 
    parentEl.on('focusout', function() { 
    // Check where focus has moved to 
    setTimeout(function() { 
     if(parentEl.find(":focus").length == 0){ 
     // Focus has moved outside the parent element 
     }else{ 
     // Focus has moved to another element within the parent element 
     } 
    }, 50) 
    }); 

50毫秒setTimeout給瀏覽器的機會將焦點移到新的元素,我們檢查了。

+1

50有意義嗎? 0在某些場景或瀏覽器下不工作嗎? – Aaronius

+0

不幸的是,這似乎並不適用於家長的div。點擊時他們似乎沒有得到焦點位。 –