我想生成带有预填充 CSS 数据的代码笔链接。
如何在 JavaScript 中以编程方式完成此操作?
我尝试将预填充的数据发布到代码笔,但无法以编程方式生成代码笔链接。
您应该使用 CodePen API。
示例:
<form action="https://codepen.io/pen/define" method="POST" target="_blank">
<input type="hidden" name="data" value='{"title": "New Pen!", "html": "<div>Hello, World!</div>"}'>
<input type="submit" value="Create New Pen with Prefilled Data">
</form>
更多信息:
理论上,您也可以使用
<a>
链接元素 - 避免使用 <form>
元素并使其可共享。但这种方法几乎没法用。
主要问题:由于GET
<p>
<a id="link" href="https://codepen.io/pen/define?data=%7B%22title%22%3A%22New%20Pen!%22%2C%22html%22%3A%22%3Cdiv%3E%27Hello%2C%20World!%27%3C%2Fdiv%3E%22%7D" target="_blank">Create prefilled codepen Link </a>
</p>
只要 GET
data
JSON 编码正确,它就可以工作。对于编码,您可以使用
encodeURIComponent()
。
让您了解字符限制:let props = {
title: "New Pen!",
html: "<p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a <em>horrible vermin.</em></p>",
css: `
@font-face {
font-family: 'ABeeZee';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/abeezee/v22/esDT31xSG-6AGleN2tCUnJ8DKpE.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'ABeeZee';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/abeezee/v22/esDR31xSG-6AGleN2tWkkA.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
body{
font-family: 'ABeeZee';
font-weight: 400;
color:red;
font-size:10em;
}`
};
let data = JSON.stringify(props);
let url = `https://codepen.io/pen/define?data=${encodeURIComponent(data)}`;
console.log('url length:', url.length)
link.href = url;
<p>
<a id="link" href="" target="_blank">Create prefilled codepen Link </a>
</p>
虽然上面的示例非常简单,仅包含 2 个字体规则和一个段落,但它已经突破了限制(1725 个字符)。