文档非常清楚如何添加自定义工具栏按钮,但我需要做的是使用按钮设置/取消设置当前所选文本的 CSS 属性。
具体来说,当选择按钮时,我需要能够将 CSS 属性“writing-mode”设置为“vertical-rl”,或者从“vertical-rl”取消设置。
我该怎么做?
要实现此功能,您需要编写一些 JavaScript 代码来与文档中选定的文本进行交互并应用所需的 CSS 属性。
function toggleWritingMode() {
// Check if any text is selected
if (window.getSelection().toString().length !== 0) {
current value
document.execCommand('styleWithCSS', false, true);
document.execCommand('styleWithCSS', false, false);
document.execCommand('insertHTML', false, '<span class="vertical-
text">' + window.getSelection().toString() + '</span>');
}
}
// Function to initialize the toolbar button
function initializeToolbarButton() {
// Create a button element
var button = document.createElement('button');
button.innerHTML = 'Toggle Writing Mode';
// Add an event listener to toggle writing mode when the button is clicked
button.addEventListener('click', function() {
toggleWritingMode();
});
// Add the button to your toolbar (assuming you have a div with id "toolbar" for your toolbar)
document.getElementById('toolbar').appendChild(button);
}
// Call the initialization function when the document is ready
document.addEventListener('DOMContentLoaded', function() {
initializeToolbarButton();
});