使用JavaScript注释CSS属性来切换样式属性

3
我想将属性列表发送到一个函数,该函数将通过注释临时禁用这些属性。这个目的类似于Chrome Dev Tools在检查元素样式时所实现的功能,不同之处在于用户不会勾选/取消勾选框,而是由JavaScript执行此操作。
function disableProperties(el, properties) {
    var property; // property value pair
    var cssStr = el.style.cssText.replace(/; /g, ";");

    for (let i = 0; i < properties.length; i++) {
        property = properties[i] + ": " + eval("el.style." + properties[i]) + ";";
        cssStr = cssStr.replace(property, "/* " + property + " */");
    }

    el.setAttribute("style", cssStr);
}

function restoreProperties(el, properties) {
    var outHtml = el.outerHTML;
    var key = 'style="';
    var idx1 = outHtml.indexOf(key) + key.length;
    var idx2 = outHtml.indexOf('"', idx1);
    var style = outHtml.substring(idx1, idx2);

    for (let i = 0; i < properties.length; i++) {
        str = "/* " + properties[i];
        let a = style.indexOf(str);
        let b = style.indexOf(" */", a + a.length) + 3;
        let comment = style.substring(a, b);
        let property = (comment).replace("/*", "").replace("*/", "");

        style = style.replace(comment, property);
    }

    el.style.cssText = style;
}

当元素被创建时,它们的样式嵌入在HTML中而不是外部CSS文件中。重要的是属性只是暂时禁用;它们以前的值必须保留。
更新: 我认为我的注释代码没有起作用,因为我试图通过请求el.style.cssText来检索注释;但是,注释只能通过outerHTML获得。
下面的代码是可行的,但我相信它可以被整理一下。如果您有关于如何改进此代码的建议,请告诉我。这里是一个演示我如何使用该代码的fiddle示例。

1
在Chrome浏览器下,你发布的代码中的属性已经正确注释(而不是被删除)。屏幕截图JSFiddle - blex
@NathanGreen 我已经删除了我的回答,因为根据你对它的评论,我认为它不是你要找的东西。你提到你会编辑问题,所以我会等待并看看是否可以根据你的编辑提供更相关的答案。 - volt
@blex 谢谢你让我知道我的代码起作用了,我一直在尝试使用JS来检索它而不是检查它。我的检索评论的代码有问题。 - Nathan Green
@volt,感谢您的代码建议;我能够从您的代码中学习,以改进我自己的其他领域。 - Nathan Green
1个回答

1
扩展Volts删除的答案,使用数据属性来存储元素的初始状态。您可以使用这些信息重置值。一个注意点是style属性是只读的,因此如果我们想要重置所有样式属性,我们必须循环所有属性。这比注释的hack方法更清晰。这适用于内联设置和类设置的样式。

const disableProperties = (el, properties) => {
  //store the style so we can restore it
  
  el.dataset.styles = JSON.stringify(el.style);
  console.log(JSON.parse(el.dataset.styles));
  properties.forEach(property => {
    el.style[property] = "unset";
  })
}

const enableProperties = (el, properties) => {
  //Get our saved initial state
  let styles = JSON.parse(el.dataset.styles);
  console.log(styles);
  properties.forEach(property => {
    el.style[property] = styles[property];
  })
}

const restoreAll = (el) => {   
  let styles = JSON.parse(el.dataset.styles);
  console.log(styles);
  /*You might think the following line should work, but the styles property is read only*/
  /*el.style = styles;*/
  /*So loop our properties instead*/
  for(prop in styles){
    if(styles.hasOwnProperty(prop)){
      el.style[prop] = styles[prop];
    }    
  }
}

document.querySelector('.child').addEventListener("click", function() {
  disableProperties(this.parentNode, ["top", "left"])
})

let enableButtons = document.querySelectorAll(".enable");

for (var i = 0; i < enableButtons.length; i++) {
  enableButtons[i].addEventListener("click", function(event) {
    let property = this.dataset.restore;
    let target = document.querySelector(this.dataset.target);
    enableProperties(target, property.split(","));
  });
}

document.getElementById("restoreAll").addEventListener("click", function() {
  restoreAll(document.querySelector(".parent"));
});
.parent {
  /*top: 50px;*/
  left: 50px;
  position: absolute;
}

.child {
  background: red;
  width: 50px;
  height: 50px;
}

.container {position:relative; height:200px;}
Click the square before restoring

<div class="container">
  <div class="parent" style="top:50px;">
    <div class="child">
    </div>
  </div>
</div>
<button id="restoreLeft" class="enable" data-restore="left" data-target=".parent">Restore Left</button>
<button id="restoreTop" class="enable" data-restore="top" data-target=".parent">Restore top</button>
<button id="restoreAll">RestoreAll</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接