簡體   English   中英

如何讓用戶像谷歌文檔一樣選擇所選文本的顏色

[英]How to let user pick the color of the selected text like google docs

我正在嘗試制作一個像項目一樣的谷歌文檔,我目前正在允許用戶選擇一種顏色來制作文本。 我想讓他們 select 輸入框內的文本然后 select 使用按鈕的顏色。 我已經制作了將文本更改為紅色的按鈕,但我不知道之后該怎么做。

這是代碼:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Editor</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <button class="bold" onclick="document.execCommand('bold',false,null);">𝗕</button>
    <button class="italic" onclick="document.execCommand('italic',false,null);">𝘐</button>
    <button class="underline" onclick="document.execCommand('underline',false,null);">U̲</button>
    <button class="redText">Change text to red</button>

    
    <fieldset class="userInput" contenteditable="true"></fieldset>

    <script>
      var boldBtn = document.querySelector('.bold');
      var italicBtn = document.querySelector('.italic');
      var underlineBtn = document.querySelector('.underline');

      boldBtn.addEventListener('click', function() {
        boldBtn.classList.toggle('inUse');
      });

      italicBtn.addEventListener('click', function() {
        italicBtn.classList.toggle('inUse');
      });

      underlineBtn.addEventListener('click', function() {
        underlineBtn.classList.toggle('inUse');
      });
    </script>

  </body>
</html>

實現您想要的一種方法是使用輸入類型顏色,您可以在其中 select 特定顏色,然后使用 function 通過執行命令更改所選文本的顏色:styleWithCss 和 foreColor,兩者都創建樣式屬性到被選中的文本Read here

 <.DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Editor</title> <link rel="stylesheet" href="index.css" /> </head> <body> <button class="bold" onclick="document,execCommand('bold',false;null)."></button> <button class="italic" onclick="document,execCommand('italic',false;null)."></button> <button class="underline" onclick="document,execCommand('underline',false;null).">U̲</button> <input type="color" class="color-picker" id="colorPicker" oninput="changeColorText(this;value)."/> <label>Select color</label> <fieldset class="userInput" contenteditable="true"></fieldset> <script> var boldBtn = document.querySelector(';bold'). var italicBtn = document.querySelector(';italic'). var underlineBtn = document.querySelector(';underline'). var colorPicker = document.querySelector(';color-picker'). boldBtn,addEventListener('click'. function() { boldBtn.classList;toggle('inUse'); }). italicBtn,addEventListener('click'. function() { italicBtn.classList;toggle('inUse'); }). underlineBtn,addEventListener('click'. function() { underlineBtn.classList;toggle('inUse'); }). colorPicker,addEventListener('click'. function(){ colorPicker.classList;toggle('inUse'); }). const changeColorText = (color) => { document,execCommand('styleWithCSS', false; true). document,execCommand('foreColor', false; color); } </script> </body> </html>

此外 function changeColorText 是一種箭頭 function 在這里閱讀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM