返回

开发一个在线检测文章中代码块占比的页面(下)

前端

自动检测文章中代码块占比的在线页面(下)

前言

在之前的文章中,我们构建了页面架构并连接了必要的 JavaScript 逻辑。现在,我们将完善这个页面,添加样式表并实现与用户交互的功能。

样式表

为了使页面美观且易于使用,我们将添加一个 CSS 样式表:

body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  line-height: 1.5;
}

h1 {
  margin-top: 0;
  margin-bottom: 10px;
}

#form-container {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 600px;
  margin: 0 auto;
}

#url-input {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

#submit-button {
  background-color: #008CBA;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

#results-container {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 600px;
  margin: 0 auto;
  margin-top: 20px;
}

#results-text {
  font-size: 16px;
}

交互逻辑

现在,我们添加与用户的交互逻辑:

  1. 获取 URL: 当用户在输入框中输入 URL 并单击“提交”按钮时,我们将获取 URL。
  2. 发送请求: 使用 JavaScript 发起到我们之前构建的 Node.js 服务器的 AJAX 请求,并传递输入的 URL。
  3. 接收响应: 服务器将返回一个包含文章文本的响应。
  4. 计算代码块占比: 使用 JavaScript 解析文章文本并计算代码块的占比。
  5. 显示结果: 将计算出的代码块占比显示在结果容器中。

以下 JavaScript 代码实现了上述交互逻辑:

// 获取 DOM 元素
const form = document.getElementById("form-container");
const urlInput = document.getElementById("url-input");
const submitButton = document.getElementById("submit-button");
const resultsContainer = document.getElementById("results-container");
const resultsText = document.getElementById("results-text");

// 添加事件监听器
form.addEventListener("submit", (e) => {
  e.preventDefault();

  // 禁用按钮
  submitButton.disabled = true;

  // 获取 URL
  const url = urlInput.value;

  // 发送 AJAX 请求
  const xhr = new XMLHttpRequest();
  xhr.open("POST", "/api/analyze");
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(JSON.stringify({ url }));

  // 接收响应
  xhr.onload = () => {
    if (xhr.status === 200) {
      const response = JSON.parse(xhr.responseText);

      // 计算代码块占比
      const codeBlockPercentage = (response.codeBlocks / response.totalLines) * 100;

      // 显示结果
      resultsText.innerText = `代码块占比:${codeBlockPercentage.toFixed(2)}%`;
      resultsContainer.style.display = "block";
    } else {
      alert("请求失败");
    }

    // 启用按钮
    submitButton.disabled = false;
  };
});

结论

通过添加样式表和交互逻辑,我们已经成功创建了一个可以在线检测文章中代码块占比的完整页面。此页面可帮助开发者快速评估文章的技术内容,并了解代码与其他内容的相对比例。

补充说明

为了提高此页面的准确性,可以考虑以下附加功能:

  • 支持多种文章格式: 除了 URL,还允许用户上传文章文件(例如,.txt.md)。
  • 可视化结果: 在结果容器中添加图表或进度条,以更直观地显示代码块占比。
  • 高级分析: 提供更详细的分析,例如每种编程语言的代码块数量分布。