【问题标题】:When using element.style = <some CSSStyleDeclaration> makes element dissapear当使用 element.style = <some CSSStyleDeclaration> 使元素消失
【发布时间】:2016-11-08 22:28:39
【问题描述】:

我使用,(请不要介意选择器,我知道它应该更改但仍然找到)。

 let leftArrow = <HTMLElement> document
  .querySelector('div[style="position: absolute; left: 6px; transform: skewX(22.6deg);' +
    ' transform-origin: 0px 0px 0px; height: 24px; width: 10px;' +
    ' box-shadow: rgba(0, 0, 0, 0.6) 0px 1px 6px; background-color: rgb(255, 255, 255);"]');

然后我使用:

let myStyle = leftArrow.style; //this gets me a CSSStyleDeclaration object
console.log(myStyle);         // those are equal objects
console.log(leftArrow.style); // those are equal objects

但是当我这样做时:

leftArrow.style = myStyle; //this should change nothing ?!

我的元素消失了?!

我的目标是使用一个类,然后这样做:

leftArrow.style = this.getStyleFromClass(selector_to_find_class_name);

但简单之后:

leftArrow.style = myStyle;

我从上面的元素变成:

<div></div>

这使得它基本上不可见。为什么?

【问题讨论】:

  • 控制台有错误提示吗?
  • 您是否要恢复应用的样式?您将需要以不同的方式来解决这个问题。

标签: javascript css dom typescript angular


【解决方案1】:

我认为您正在尝试做的是将原始内联样式应用回去。为此,您可以使用 cssText 获取值,然后将其设置回来。

var div = document.getElementById("x");
var backUp = div.style.cssText;
div.style.backgroundColor = "yellow";
div.style.color = "blue";
window.setTimeout( function () {
  div.style.cssText = backUp;
}, 4000);
&lt;div id="x" style="background-color:red"&gt;Hello&lt;/div&gt;

【讨论】:

    【解决方案2】:

    leftArrow.style = myStyle; //这应该不会改变什么?!

    是的,但前提是你有:

    let myStyle = leftArrow.style; //this gets me a CSSStyleDeclaration object
    letArrow.style = myStyle;
    

    这很可能不是您拥有的代码,而是您正在动态生成对象。 不要直接分配给样式。而是分配给style 的成员,例如letArrow.style.color = "red"

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 2016-12-02
      • 1970-01-01
      相关资源
      最近更新 更多