2013-07-08 39 views
5

嗨,朋友,我有一個textarea,我想使用此元素的animate()css()函數。只關注一次 - jquery

css()功能正常,但問題是focus() func。頁面加載後一切都很好,

當我集中到textarea它的高度增加了50px,但是當我模糊,然後再次聚焦到textarea然後高度再次增加50px。我不想使用blur()函數。

我的問題是關於使用focus()函數。我想每頁加載一次使用focus()

<script> 
       $(document).ready(function(){ 
        $("#sharePost").focus(function(){ 
        $(this).animate({height:"+=50px"}); 
        $(this).css("background-color","#ffccdd"); 
        }); 
        $("#sharePost").blur(function(){ 
        //$(this).animate({height:"-=50px"}); 
        }); 
       }); 
</script> 

回答

8

觸發事件只有一次,你可以使用one()功能,附加一個事件偵聽器,然後在第一時間它發射後刪除它:

$(document).ready(function(){ 
    $("#sharePost").one('focus', function(){ 
     $(this).animate({height:"+=50px"}); 
     $(this).css("background-color","#ffccdd"); 
    }); 

}); 

Working Demo

2

您可以使用jQuery's .one() function輕鬆做到這一點。這隻會觸發事件處理程序,最多隻會爲其附加的元素觸發一次。

在這種情況下,您不需要使用$(document).ready(function()...(除非您的腳本在您的#sharePost元素前之前)。作爲一個例子,你可能只是這樣做:

$("#sharePost").one("focus", function(){ 
    $(this).animate({height:"+=50px"}); 
    $(this).css("background-color","#ffccdd"); 
}); 

的元素有關的第一個focus後,包含您的.animate和.css的處理程序將不會再運行。如果你想要的話,你可以從那裏走,當焦點離開元素時縮小。