2011-09-22 52 views
0

我有一個textarea,輸入文本和輸入收音機評論表。首先,你會看到textarea。如果你點擊它,整個表單將展開。當您在表單外單擊並且字段沒有值時,表單應該再次減少到textarea。這也適用。窗體展開/減少處理與jquery

問題是,當您在表單內從一個字段切換到另一個字段時,表單將縮小並展開,並且一次又一次。 if ($this.not(":focus"))不會幫助。
任何想法?

HTML

<div id="commentBox"> 
    <form action="..."> 
     <label for="comment">Write a comment...</label> 
     <textarea id="comment"></textarea> 

     <div class="expandBox" style="display: none"> 
      <label for="title">Title</label> 
      <input type="text" id="title" /> 
      <br /> 
      <label for="email">E-Mail *</label> 
      <input type="text" id="email" /> 
      <br /> 
      <label for="name">Newsletter</label> 
      <input type="radio" id="yes" name="newsletter" /><label for="yes">ja</label> 
      <input type="radio" id="no" name="newsletter" /><label for="no">nein</label> 
      <br /> 
      <label for="name">Name *</label> 
      <input type="text" id="name" /> 
      <br /> 
      <input type="submit" value="senden" /> 
     </div> 

    </form> 
</div> 

jQuery的片斷(在domready中斷過程)

$("#commentBox").find("input,textarea").each(function() { 
    var $this = $(this); 
    var $expandBox = $this.parents("#commentBox").find(".expandBox"); 

    $this.focus(function() { 
      $expandBox.slideDown(250); 
    }); 

    $this.blur(function() { 
      if ($this.val() === "" && $this.not(":focus")) { 
        $expandBox.slideUp(250); 
      } 
    }); 
}); 

回答

1

的問題是,當你輸入/文字區域之間切換,focus()觸發新聚焦元件上,並且blur()在最後一個。

$expandBox因此被要求爲slideUp() AND slideDown()

要解決此問題,您必須告訴這些動畫,以便在調用這些動畫時停止以前的動畫。這樣,slideUp()將被調用,並立即停止slideDown()

爲此使用stop()

$("#commentBox").find("input,textarea").each(function() { 
    var $this = $(this); 
    var $expandBox = $this.parents("#commentBox").find(".expandBox"); 

    $this.focus(function() { 
      $expandBox.stop().slideDown(250); 
    }); 

    $this.blur(function() { 
      if ($this.val() === "" && $this.not(":focus")) { 
        $expandBox.stop().slideUp(250); 
      } 
    }); 
}); 
+0

我相信你只需要在焦點事件中調用'stop()'。 – Lazarus

+0

是的,停止的事情解決了它!謝謝。 – Thomas