在哪里存储临时实时 <style> 样式

pix*_*123 5 html javascript css jquery

我正在尝试创建一个网站构建器(拖放页面构建器),并且想知道当有人更改元素的样式时将样式存储在哪里。例如,在 WordPress 中,您可以在定制器中输入您自己的自定义 CSS(图片示例:https : //i.imgur.com/qaUiVl6.png

在 Wix 或 Google Chrome Inspect Element 等其他页面构建器中,您可以单击按钮来启用或禁用样式。

在对页面进行当前/实时 CSS 编辑时,这些样式保存在何处以及如何保存?(我不是在谈论数据库,因为代码尚未保存。我在谈论在进行现场更改时,这些“临时/实时”CSS 样式在哪里保存?)

Tra*_*ton 6

您可以使用 CSSStyleSheet API 在内存中生成样式表,然后使用插入和删除方法随意在样式表中添加或删除规则。当用户完成修改后,您可以将生成的样式表传回服务器端以保存烫发。

参考文档可以在这里找到:https : //developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet#Methods

兼容 IE9+ 和所有其他现代浏览器,因此具有良好的覆盖范围。

下面的快速和肮脏的例子。

var style = (function() {
    // Create the <style> tag
    var style = document.createElement("style");
    // Add the <style> element to the page
    document.head.appendChild(style);
    return style;
})();

function AddRule(){
 //append rule from textbox to ss here
  style.sheet.insertRule(document.getElementById("cssIn").value, 0);
  document.getElementById("appliedRules").innerHTML = '';
  var rules = style.sheet.cssRules;
  for (var r in rules) {
    if(rules[r].cssText){
     document.getElementById("appliedRules").innerHTML += '<br>' +  rules[r].cssText;
    }
  }
}
//enable this to see your special prize in the console
//console.log(style.sheet);
Run Code Online (Sandbox Code Playgroud)
<div class="test"> here we go</div>
Add Rule: <input type="text" id="cssIn" value=".test {color:blue}">
<button type="button" onClick="AddRule();">Add</button>

<div id="appliedRules"></div>
Run Code Online (Sandbox Code Playgroud)


Kod*_*son 4

这是一个简单的概念验证,演示了如何使用纯 JavaScript 来完成此操作。只需单击“保存”按钮即可查看文本区域中的 CSS 是否应用到页面。CSS 仅存储为 textarea 元素的输入值。您还可以通过使用 localStorage 和 iframe 或 Shadow dom 使其变得更复杂,这样您只影响“预览”窗格。但这只是一个演示。

function saveStyles() {
    document.querySelector('#style-container').innerHTML = document.querySelector('#style-input').value;
}
Run Code Online (Sandbox Code Playgroud)
#style-input {
  width: 100%;
  box-sizing: border-box;
  display: block;
  margin-bottom: 8px;
}
Run Code Online (Sandbox Code Playgroud)
<style id="style-container"></style>
<textarea id="style-input" rows="5">body{background:red;}</textarea>
<button onclick="saveStyles()">Save</button>
Run Code Online (Sandbox Code Playgroud)