2016-07-06 99 views
0

我使用,(请不要介意选择器,我知道它应该改变,但它仍然被发现)。当使用element.style = <some CSSStyleDeclaration>使元素消失

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 ?! 

我的元素dissappears?!

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

leftArrow.style = myStyle; 

从上一个我的元素变成:

leftArrow.style = this.getStyleFromClass(selector_to_find_class_name); 

但经过简单的

<div></div> 

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

+1

是否有在控制台中的任何错误消息? –

+0

您是否尝试恢复应用的样式?你将需要以不同的方式来解决这个问题。 – epascarello

回答

0

我认为你要做的是将原有的内联样式应用回来。为此,您可以使用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>

1

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

是的,但只有当你有:

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

这是最有可能不是你的代码,你正在生成的飞行物体。 请勿直接分配到样式。而是分配给style的成员,例如letArrow.style.color = "red"