2013-07-08 29 views
1

我試圖將焦點放在隱藏的div上,它在調用.show()函數後顯示。四,試了幾件事情,包括顯示()。對焦()或分裂它分爲將焦點設置爲顯示後的div

$(".messageDisplayArea").show(); 
$("#message_display_area").focus(); 

在div顯示出來,但頁面不焦點切換到它。

<script> 
    function showMessage(id, row) { 
      selectRow(row);   
      $(".messageDisplayArea").show();   
      $("#message_display_area").focus(); 
    } 

</script> 


<div class="messageDisplayArea" id="message_display_area" style="display: none;"> 

<p> Test Test Test </p> 

</div> 

我錯過了什麼?它所在的頁面非常大,div出現在頁面的底部。我希望瀏覽器跳下來,並把新的div在焦點

+0

你想把重點放在'div'元素上是什麼意思? – Sergio

+0

也許我誤解了.focus()函數。我想要做的是給出現在這個新的div的文字焦點。正如在瀏覽器跳轉到div,因爲它出現在屏幕的底部,用戶甚至不知道它在那裏,直到他們滾動下來 – CoffeePeddlerIntern

回答

2

替換此行:

$("#message_display_area").focus(); 

這一行:

window.location.hash = "message_display_area"; 
+0

非常感謝,這正是我想要的!簡短,甜美,簡單 – CoffeePeddlerIntern

1

焦點並不意味着您的頁面滾動到該元素,實際上經常用於獲取光標的窗體控件。

你需要的其實是一個scrollToElement()函數計算頁面新創建的div的偏移和滾動頁面到該位置,好一個描述如下:jQuery scroll to element

+0

感謝您的帖子,你的時間表示讚賞! – CoffeePeddlerIntern

2

至於你給我們的代碼,你應該有什麼工作,就像這個小提琴一樣。

http://jsfiddle.net/SuERE/

http://jsfiddle.net/SuERE/1/

HTML:

<button type="button">Show and Focus</button> 
<div style='height:700px'></div> 
<input type="text" id="input" style='display:none;'/> 

的Javascript:

$("button").on("click",function(){ 
    $("#input").show(); 
    $("#input").focus(); 
}); 
+0

謝謝您花時間發佈和幫助! – CoffeePeddlerIntern

0

你可以做的另一件事是tabindex屬性添加到div元素。這將使focus方法能夠執行並找到它並自動移至該方法。

<div id="message-display-area" tabindex=1000>...</div>

JSFiddle顯示它的工作。