【问题标题】:Using tag key to insert text and change the size of text in Web application在 Web 应用程序中使用标签键插入文本并更改文本大小
【发布时间】:2019-11-22 11:26:46
【问题描述】:

我正在为课程作业制作一个基本的在线编辑界面,我想使用键盘事件。 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>



【问题讨论】:

  • inputList 是一个类而不是一个 id,即class="inputList" vs id="inputList"

标签: javascript html css events


【解决方案1】:

<!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 的属性。

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    相关资源
    最近更新 更多