2015-10-30 13 views
0

我正在嘗試使輸入框看起來像有一個佔位符,表示用戶名,但是當選中該框時,它會移動並更改爲較暗的顏色以類似於標籤。我遇到的問題是每當我將鼠標懸停在該框上時,它將完成動畫,但是立即撤消它,將文本恢復爲看起來像佔位符。我還想製作我的Javascript/JQuery代碼,以便在框中輸入任何內容時,文本將保留爲標籤,即使未被選中也不會返回佔位符。我的另一個問題是,我不知道JQuery命令來判斷是否選擇了輸入框。我公司供應沿着下面的所有我的代碼並鏈接到CodePen它具有動畫取決於輸入框是否爲空並留在那裏?

<div id='inputdiv'> 
    <input id='textinp'> 
</div> 
<h4>Username</h4> 


#textinp { 
    border: none; 
    width: 200px; 
    height: 30px; 
    font-size: 20px; 
    margin-left: 5px; 
    font-family: 'Roboto', sans-serif; 
    background: rgba(0, 0, 0, 0); 
} 

input:focus { 
    outline: 0; 
} 

#inputdiv { 
    width: 200px; 
    height: 32px; 
    margin: 0 auto; 
    margin-top: 70px; 
    border-top: 1px solid black; 
    border-right: none; 
    border-left: 1px solid black; 
    border-bottom: none; 
    z-index: -2; 
} 

h4 { 
    font-family: 'Roboto', sans-serif; 
    font-size: 20px; 
    position: relative; 
    bottom: 53px; 
    left: 575px; 
    color: #C2C2C2; 
    z-index: -1; 
} 


$(document).ready(function() { 
    $("#inputdiv").mouseenter(function() { 
    $("h4").animate({ 
     left: '470px', 
     color: '#00000' 
    }); 
    if ($('#textinp').val() == '') { 
     $("h4").animate({ 
     left: '580px', 
     color: '#C2C2C2' 
     }); 
    } 
    }); 
}); 

CodePen

回答

1

嘗試使用hover()方法來代替。作爲第一個參數定義在hoverIn上執行的函數(在鼠標進入時),作爲在hoverOut上執行的第二個函數(在鼠標離開時)。

這裏是你的榜樣更新: http://codepen.io/anon/pen/LprybQ

+0

謝謝你,基本解決了。唯一的另一個問題是,當我點擊框然後開始輸入時,我沒有將它懸停在它上面,那麼用戶名將回到輸入框。如果有一個JQuery命令喜歡.focus()或者什麼時候會告訴我什麼時候選擇了一個輸入框,我認爲它會解決這個問題,或者我可以將if語句移到別的地方,也可以。感謝您的幫助! – Joshua

+1

我更新了筆。看一看。 – Justas