Skip to content

第 23 期(ECMAScript-语法):字符串对象HTML格式替代方法 #26

Open

Description

@wingmeng

题目:

已知有如下 HTML 结构,请编写函数 format,实现点击对应按钮后对 #str 文本进行加粗、斜体、上标或下标格式化。

提示:请使用 HTML 格式替代方法

<span id="str">儿童节快乐!</span>
<p>
  <button onclick="format(1)">加粗</button>
  <button onclick="format(2)">斜体</button>
  <button onclick="format(3)">上标</button>
  <button onclick="format(4)">下标</button>
</p>

参考答案:

function format(type) {
  let text = str.innerText || str.textContent;
  let result;

  switch(type) {
    case 1:
      result = text.bold();
      break;
    case 2:
      result = text.italics();
      break;
    case 3:
      result = text.sup();
      break;
    case 4:
      result = text.sub();
      break;      
    default:
      result = text;  
  }

  str.innerHTML = result;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions