[英]document.execCommand not working properly
I am working on a really simple JS project (for my client, so can't use jQuery for this, meh.) 我正在开发一个非常简单的JS项目(对于我的客户,所以不能为此使用jQuery,对。)
So basically I have a few buttons like this: 所以基本上我有几个这样的按钮:
button.onClick="document.execCommand('bold', false, null);";
and others like italic, underline, etc. 以及其他如斜体,下划线等。
The problem is that they are not working. 问题在于它们不起作用。 I know for sure that execCommand works, because I tested it with a timer and it does work.
我肯定知道execCommand可以工作,因为我使用计时器对其进行了测试并且它确实可以工作。 The reason that it's not is that when I click on it, the text from the contentEditable=true div gets unselected.
不是这样的原因是,当我单击它时,来自contentEditable = true div的文本被取消选择。
Is there any way to avoid this? 有什么办法可以避免这种情况?
Thanks in advance. 提前致谢。
boldBtn = document.createElement('a');
boldBtn.innerHTML = "make text bold";
document.getElementById("toolbox").appendChild(boldBtn);
boldBtn.onClick="document.execCommand('bold', false, null);";
Why are you using exeCommand exactly? 为什么要精确使用exeCommand?
You can do this via vanilla JavaScript just fine. 您可以通过普通JavaScript很好地完成此操作。
document.getElementById("boldBtn").style.fontWeight = "bold";
or since you already have a reference 或者因为您已经有参考
boldBtn.style.fontWeight = "bold";
If you do javasript, you'd rather set the listeners to real functions, not strings that are functions. 如果您使用javasript,则宁愿将侦听器设置为实际函数,而不是作为函数的字符串。
boldBtn.setAttribute("href", "#");
boldBtn.onClick = function()
{
document.execCommand("bold", false, null); //or maybe exec bold(false); directly ?
return false;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.