提问者:小点点

如何在网页中显示多语言,多文件的代码块,类似于在条形文档中的这个例子?


在此网页上,https://stripe.com/docs/payments/accept-a-payments#web-Setup

有一些代码片段分布在不同语言(使用选项卡)和不同文件(在同一选项卡内)的示例

我想知道怎样才能达到同样的效果,同时也允许复制到剪贴板

请看下面的图片了解我的意思


共1个答案

匿名用户

这是相当丑陋的(需要更多的css和更好的javascript),但这是一个开始,让您知道如何继续:

代码en

null

let data = {
  javascript: [
    {
      filename: "javascript1.js",
      content: "//this is the content of file 1"
    },{
      filename: "file2.js",
      content: "//this is the content of file 2"
    }
  ],
  python: [
    {
      filename: "python1.py",
      content: "#this is the content of file 1"
    },{
      filename: "python2.py",
      content: "#this is the content of file 2"
    },{
      filename: "python3.py",
      content: "#this is the content of file 3"
    }
  ],
  'C++': [
    {
      filename: "c++1.cpp",
      content: "//this is the content of file 1"
    },{
      filename: "header1.h",
      content: "//this is the content of header 1"
    }
  ]
}

function clearElement(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild)
  }
}

function setupCodeBlocks(targetElementId) {
  let container = document
    .getElementById(targetElementId)
    
  clearElement(container)
    
  let languageNav = document.createElement('nav')
  
  let filesDiv = document.createElement('div')
    
  let languages = Object.keys(data)
  languages.forEach(language => {
    let languageButton = document.createElement('button')
    languageButton.id = "show:" + language
    languageButton.appendChild(
      document.createTextNode(language)
    )
    languageButton.classList.add('language')
    languageButton.addEventListener('click', (e) => {
      show(language)
    })
    
    languageNav.appendChild(languageButton)
  })
  
  function show (language) {
    clearElement(filesDiv)
    let files = data[language]
    files.forEach(file => {
      let fileSection = document.createElement('div')
      let fileTitle = document.createElement('h3')
      fileTitle.appendChild(
        document.createTextNode(file['filename'])
      )
      let fileContent = document.createElement('textarea')
      fileContent.value = file['content']
      
      fileSection.appendChild(fileTitle)
      fileSection.appendChild(fileContent)
      filesDiv.appendChild(fileSection)
    })
  }
  
  container.appendChild(languageNav)
  container.appendChild(filesDiv)
}

setupCodeBlocks('codeblocks')
#codeblocks {
  border: 1px solid #666;
  
}
<h1>
 multi language/files code blocks :
</h1> 

<div id="codeblocks">
  ...loading
</div>