[英]Using jQuery selector and setSelectionRange is not a function
我已經在下面組裝了一個基本的jfiddle。 由於某種原因,我的選擇器用於檢索textarea框以設置值,但選擇器不能使用setSelectionRange函數。 在控制台上,你會發現.setSelectionRange不是函數的錯誤。
代碼(請參考jfiddle): selector.setSelectionRange(carat,carat);
HTML:
<input type="search" value="Potato Pancakes" id="search">
JQUERY:
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
$("#search").putCursorAtEnd();
校驗:
http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
對我來說這是一個很好的解決方案
selector[0].setSelectionRange(start ,end);
但我想補充一點。 我注意到setSelectionRange
是元素獲得焦點后異步可用的東西。
var element = selector[0];
element.addEventListener('focus', function() {
element.setSelectionRange(start, end);
});
element.focus();
您也可以使用:
element.selectionStart = start;
element.selectionEnd = end;
你可以試試這對我有用。 我用它來從單獨的地址字段構建一個地址,然后復制粘貼。
HTML
<div id="d_clip_container" style="position:relative">
(<a href="#" id="d_clip_button">copy to clipboard</a>)
</div>;
<textarea id="clip" rows="0" cols="0" style="border:none;height:0;width:0;"></textarea>
jQuery
$(document).ready(function() {
$('#d_clip_button').click(function() {
//get all the values of needed elements
var fName = $("#firstName").val();
var lName = $("#lastName").val();
var address = $("#Address").val();
var city = $("#City").val();
var state = $("#State").val();
var zip = $("#Zip").val();
//concatenate and set "clip" field with needed content
$('#clip').val(fName + " " + lName + "\n" + address + "\n" + city + ", " + state + " " + zip);
//Do it
if(copyToClipboard('#clip')) {
alert('text copied');
} else {
alert('copy failed');
}
});
});
function copyToClipboard(elem) {
// set focus to hidden element and select the content
$(elem).focus();
// select all the text therein
$(elem).select();
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// clear temporary content
$(target).val('');
return succeed;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.