javascript - 复制带有颜色和样式的文本
问题描述
这是复制文本的 JavaScript 代码:
$(function() {
$("#copyAndopenOutlook").click(function(e) {
e.preventDefault();
// Code below
var newLine = "\n";
var emailBodyText = "";
emailBodyText = emailBodyText + "This line I want bold" + newLine;
emailBodyText = emailBodyText + "This is just another line for practice" + newLine + newLine;
emailBodyText = emailBodyText + "This is the last line, I want it green color";
const el = document.createElement('textarea');
el.value = emailBodyText;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
// alert("Text is copied, and can now be pasted into outlook new mail");
var mail = document.createElement("a");
mail.href = "mailto:someone@example.com?subject=Test ";
mail.click();
// Code Above
});
});
我想将其复制并粘贴到我正在工作的 Outlook 中,但是如何使第一行变为粗体,最后一行变为绿色?我尝试过添加<b>
代码和颜色,但它只是复制和颜色标签。
解决方案
如果要标记文本,则需要一个支持 HTML 内容的元素。例如,这是一个使用 adiv
和Selection
object的版本。
$(function() {
$("#copyAndopenOutlook").click(function(e) {
e.preventDefault();
// Code below
const newLine = "\n";
let emailBodyText = "";
emailBodyText = emailBodyText + "<strong>This line I want bold</strong>" + newLine;
emailBodyText = emailBodyText + "This is just another line for practice" + newLine + newLine;
emailBodyText = emailBodyText + "<span style='color: green'>This is the last line, I want it green color</span>";
const el = document.createElement('div');
el.innerHTML = emailBodyText;
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const sel = getSelection();
sel.setBaseAndExtent(el, 0, el, el.childNodes.length);
document.execCommand('copy');
document.body.removeChild(el);
alert("Text is copied, and can now be pasted into outlook new mail");
/*
var mail = document.createElement("a");
mail.href = "mailto:someone@example.com?subject=Test ";
mail.click();
*/
// Code Above
});
});
<input type="button" id="copyAndopenOutlook" value="Copy">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
一些真正过时的浏览器可能不支持该Selection
对象,但任何现代浏览器都会支持。
您可能需要<br>
代替\n
,或者如果“行”实际上是段落,也许<p>...</p>
.
推荐阅读
- java - 在 Hibernate 多租户配置中禁用 Spring 数据源配置
- amazon-web-services - 该工厂未使用火花流和 AWS 创建的套接字
- python - 使用字符串方法过滤列值上的行
- php - 从php添加逗号Json
- javascript - 在 Mongoose 中测试验证而不访问数据库
- windows - 管理员与非管理员模式 - 无法覆盖变量,因为变量已被优化
- c# - 使用 mysql 参数时未填充 Datagrid 视图
- vba - 嵌套如果 - 可能更好的解决方案?
- java - Programmatically creating a rectangular Shape with a rectangular cutout for a Button
- laravel - Laravel:按关系 AS 列按父级排序