2017-03-16 43 views
2

我有很多輸入字段,我需要重複填寫,所以我通常使用標籤來瀏覽表單。如何防止在輸入間切換時突出顯示所有文本?

字段具有需要預設的默認後綴值。當我用鼠標點擊輸入時,它會按預期工作。

但是,當我在輸入之間選項卡時,它會選擇所有文本,這在我的情況下是不受歡迎的行爲。

看一看這樣的:

function setCaretPosition(elem, caretPos) { 
 
    if (elem == null) return; 
 
    if (elem.createTextRange) { 
 
    var range = elem.createTextRange(); 
 
    range.move('character', caretPos); 
 
    range.select(); 
 
    } else if (elem.selectionStart) { 
 
    elem.focus(); 
 
    elem.setSelectionRange(caretPos, caretPos); 
 
    } else { 
 
    elem.focus(); 
 
    } 
 
} 
 

 
$(document).ready(function() { 
 
    $('input').focus(function() { 
 
    setCaretPosition(this, 0); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="input1" value=" km/h" /> 
 
<input type="text" id="input2" value=" kg" />

  • 當你點擊裏面任意輸入,插入符年初設定。
  • 當你標籤輸入之間沒有設置插入符號。相反,整個輸入內容是重點。

如何在使用標籤導航時防止文本輸入對其內容進行重點處理?

我更喜歡沒有使用setTimeout(如果有可能的話)的答案。

+0

可能重複[有沒有一個函數來取消所有使用JavaScript的文本?](http://stackoverflow.com/questions/6562727/is-there-a-function-to-deselect-all-text-使用-javascript) – imtheman

+1

如果你認爲它是重複的,爲什麼你不投票結束重複作爲一個原因? –

+0

你確定點擊時它正在工作嗎?單擊時,脫字符號不會移到位置0! –

回答

3

在Chrome和瀏覽器(不工作的邊緣和Firefox),簡單地說:

<input type="text" value=" km/h" onfocus="this.setSelectionRange(this.value.length, this.value.length)"/> 
 
<input type="text" value=" kg" onfocus="this.setSelectionRange(this.value.length, this.value.length)"/>

在Firefox和Chrome(不工作的邊緣和瀏覽器)

jQuery.fn.putCursorAtEnd = function() { 
 
    return this.each(function() { 
 
    // Cache references 
 
    var $el = $(this), el = this; 
 
    
 
    // Timeout seems to be required for Firefox 
 
    setTimeout(function() { 
 
     el.setSelectionRange($el.val().length, $el.val().length); 
 
    }, 0); 
 
    }); 
 
}; 
 

 
var searchInput = $("input"); 
 

 
searchInput.on("focus", function() { // could be on any event 
 
    searchInput.putCursorAtEnd() 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" value=" km/h" /> 
 
<input type="text" value=" kg" />

+0

對不起,但它不起作用。當我關注第一個輸入並單擊Tab時,它將重點放在第二個輸入並選擇其所有內容。測試最新的Firefox。 – stil

+0

可以確認FF的行爲不同:( –

+0

也確認,在Chrome和瀏覽器上工作,不在Firefox上工作,邊緣將查看它 – Mindless

相關問題