我有以下代码:
<select id="fonts">
<option value = "Times New Roman">Times New Roman</option>
<option value = "Monospace">Monospace</option>
<option value = "Sans-Serif">Sans Serif</option>
<option value = "Arial">Arial</option>
</select>
<div id = "text"contenteditable = "true">
</div>我想使用document.execCommand()方法,其中字体将根据从选项列表中选择的字体名称进行更改。
我试过了:
<option value = "Monospace" document.execCommand('fontName', true, Monospace)>Monospace</option>但是我似乎不能正确地将它与选项列表连接起来,结果是什么都没有。如何根据您使用此方法选择的内容来实现字体更改?我知道可以通过按钮来使用它们,但是我很好奇是否可以通过一个选项标签来实现它?
发布于 2020-10-10 22:57:05
尝尝这个
<select id="mySelect" onchange="myFunction()">
<option value = "Times New Roman">Times New Roman</option>
<option value = "Monospace">Monospace</option>
<option value = "Sans-Serif">Sans Serif</option>
<option value = "Arial">Arial</option>
...
</select>
<div id = "text1" contenteditable = "true">
<p>Dummy Text</p>
</div>
<script>
function myFunction() {
var x = document.getElementById("text1");
selectElementContents(x); // this will select the whole text else or you can skip this if not requrired
document.execCommand("fontName", false, 'monospace'); //replace monospace with selected font
window.getSelection().empty(); // unselects the selected text
}
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
</script>发布于 2020-10-10 22:51:27
您可以使用onclick javascript来完成此操作。
例如--
<p id="para1"> somthing here..</p>
<p onclick="changeText()"> Click here to change thext style to <b>Monospace </b> </p>
<script>
function changeText(){
document.getElementId("para1").style = "font-family:monospace;";
}
</script>要更改网站中的所有文本,请执行以下操作...
<body id="body-text" >
<p id="para1"> somthing here..</p>
<p onclick="changeText()"> Click here to change thext style to <b>Monospace </b> </p>
<script>
function changeText(){
document.getElementId("body-text").style = "font-family:monospace;";
}
</script>
</body>发布于 2020-10-10 22:55:55
只要使用CSS即可。你在做所有开发人员都在做的事情,把时间花在有一个简单答案的事情上。
我不知道什么是execCommand,但使用vanilla时,我会向on change事件添加一个侦听器,然后对其下的任何类别进行css并更改文本。
https://stackoverflow.com/questions/64294634
复制相似问题