我正在使用来自http://snippets.dzone.com/posts/show/4973的一些 JavaScript以及scrollTop
下面的建议来创建一个书签,用于将预设的文本字符串插入到 Blogger 的新帖子textarea
中。代码如下所示:
//IE support
if (document.selection) {
myField.focus();
//in effect we are creating a text range with zero
//length at the cursor location and replacing it
//with myValue
sel = document.selection.createRange();
sel.text = myValue;
//Mozilla/Firefox/Netscape 7+ support
} else if (myField.selectionStart || myField.selectionStart == '0') {
myField.focus();
//Here we get the start and end points of the
//selection. Then we create substrings up to the
//start of the selection and from the end point
//of the selection to the end of the field value.
//Then we concatenate the first substring, myValue,
//and the second substring to get the new value.
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
myField.setSelectionRange(endPos+myValue.length, endPos+myValue.length);
} else {
myField.value += myValue;
}
}
以及下面的建议:
//add this to the start of function
textAreaScrollPosition = myField.scrollTop;
//add this to end of the function
myField.scrollTop = textAreaScrollPosition;
该scrollTop
建议在 Firefox 中失败,而是将浏览器中的当前页面替换为textAreaScrollPosition
.
我将此添加到书签的夹层版本的前面:
javascript:var myField=document.getElementById('postingHtmlBox');var myValue='lol';
总而言之:
javascript:var myField=document.getElementById('postingHtmlBox');
var myValue='lol';
var textAreaScrollPosition=myField.scrollTop;
if(document.selection){myField.focus();
sel=document.selection.createRange();
sel.text=myValue;
}else if(myField.selectionStart||myField.selectionStart=='0'){myField.focus();
var startPos=myField.selectionStart;
var endPos=myField.selectionEnd;
myField.value=myField.value.substring(0,startPos)+myValue+myField.value.substring(endPos,myField.value.length);
myField.setSelectionRange(endPos+myValue.length,endPos+myValue.length);
}else{myField.value+=myValue;
}myField.scrollTop=textAreaScrollPosition;
但是,没有换行符。
我还不是一个 JS 向导。我只是想帮助一个非技术朋友用 Blogger 做一些复杂的事情。有任何想法吗?
编辑:除了添加原始页面检测并用提示框替换预设文本外,我还可以通过添加myField.focus();
到末尾来解决原始问题:
javascript:if(document.getElementById('postingHtmlBox')){var myField=document.getElementById('postingHtmlBox');
var myValue=prompt('Insert text here.');
var textAreaScrollPosition=myField.scrollTop;
if(document.selection){myField.focus();
sel=document.selection.createRange();
sel.text=myValue;
}else if(myField.selectionStart||myField.selectionStart=='0'){myField.focus();
var startPos=myField.selectionStart;
var endPos=myField.selectionEnd;
myField.value=myField.value.substring(0,startPos)+myValue+myField.value.substring(endPos,myField.value.length);
myField.setSelectionRange(endPos+myValue.length,endPos+myValue.length);
}else{myField.value+=myValue;
}myField.scrollTop=textAreaScrollPosition;
myField.focus();
};
不确定最后一个分号是否是绝对必要的,但哦,解决方案!