javascript - 当使用 element.style = <some CSSStyleDeclaration> 使元素消失

标签 javascript css dom typescript angular

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

 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>

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

最佳答案

我认为您正在尝试做的是将原始内联样式应用回去。为此,您可以使用 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);
<div id="x" style="background-color:red">Hello</div>

关于javascript - 当使用 element.style = <some CSSStyleDeclaration> 使元素消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38231316/

相关文章:

javascript - 按字母顺序对关联数组/javascript 对象进行排序

javascript - 如何在以声明方式创建自定义 Dojo 小部件后检索它们

javascript - React onWheel 处理程序无法阻止Default,因为它是一个被动事件监听器

javascript - 在 asp.net 中处理任务时间

javascript - angular.toJson/JSON.stringify 值不正确?

html - 悬停菜单不显示

java - 添加 css a :hover dynamically in VB code behind

javascript - 将鼠标悬停在一个元素上会使它产生动画,而不仅仅是改变它的 CSS 属性

Javascript 以 ID 中的子元素为目标

Java:获取 org.w3c.dom 文档中元素的 xpath