下面的示例将标记 [code] 和 [/code] 写入 textarea 中的选定文本,但仅应用于字符串的开头和结尾...我希望将 [code] 和 [/code] 应用于每个将换行符视为新字符串的字符串的一部分...
发布的示例执行:
[code]test
test
test[/code]
我想申请:
blablabla...
[code]test[/code]
[code]miao miao[/code]
[code]this is teh 3rd string[/code]
etcetera, some extra string
如您所见,我想仅应用代码选择的字符串,并考虑带有换行符的新字符串...在纯javascript中可能吗?没有 jquery 或 mootools,请仅使用独立脚本...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>[javascript code]</title>
<script language="JavaScript" type="text/javascript">
var myValueBefore = "[code]";
var myValueAfter = "[/code]";
function applyCode(myField, myValueBefore, myValueAfter) {
if (document.selection) {
myField.focus();
document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;
} else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValueBefore+ myField.value.substring(startPos, endPos)+ myValueAfter+ myField.value.substring(endPos, myField.value.length);
}
}
</script>
</head>
<body>
<br><br><br>
<table align="center" border="0" cellpadding="15" cellspacing="0" width="70%">
<tr>
<td>
<form action="#" method="post">
<input type="button" value="Apply Code" onclick="javascript:applyCode(test, myValueBefore, myValueAfter);"><br>
<textarea rows="5" cols="130" name="test"></textarea>
</form>
</td>
</tr>
</table>
</body>
</html>