首页 > 解决方案 > 在 Web 应用程序中使用标签键插入文本并更改文本大小

问题描述

我正在为课程作业制作一个基本的在线编辑界面,我想使用键盘事件。tab 键应该插入文本,这是可行的,但它也应该减小该行上文本的大小。当我使用 getElementById 时,会显示一条错误消息:无法读取 null 的属性“样式”。我该怎么做?

<!DOCTYPE html>
<html>

<head>
  <title>Editor</title>
  <link rel="stylesheet" href="stylesheet.css">
  <link rel="shortcut icon" href="">
</head>

<body>
<aside class="bar">
  <div id="heading-container"></div>
</aside>
  <div id="inputArea">
    <div id="bulletPoints" contenteditable="true">
      <div id="divList" contenteditable="true">
        <ul class="inputList">
          <li id="outlineList"></li>
        </ul>
      </div>
    </div>
  </div>
  <script>
     window.onload = () => {
     window.addEventListener("keydown", checkKeyPress);

      function checkKeyPress(key){
         if (key.keyCode === 9){
         key.preventDefault();
         document.execCommand("insertText", true, "    ");
         document.getElementById("inputList").style.fontSize = "smaller";
        }
       }
     };
  </script>
</body>
</html>



标签: javascripthtmlcssevents

解决方案


<!DOCTYPE html>
<html>

<head>
  <title>Editor</title>
  <link rel="stylesheet" href="stylesheet.css">
  <link rel="shortcut icon" href="">
</head>

<body>
<aside class="bar">
  <div id="heading-container"></div>
</aside>
  <div id="inputArea">
    <div id="bulletPoints" contenteditable="true">
      <div id="divList" contenteditable="true">
        <ul class="inputList" id="inputList">
          <li id="outlineList"></li>
        </ul>
      </div>
    </div>
  </div>
  <script>
     window.onload = () => {
     window.addEventListener("keydown", checkKeyPress);

      function checkKeyPress(key){
         if (key.keyCode === 9){
         key.preventDefault();
         document.execCommand("insertText", true, "    ");
         document.getElementById("inputList").style.fontSize = "smaller";
        }
       }
     };
  </script>
</body>
</html>

您缺少 id 作为ul.


推荐阅读