JavaScript&复制风格 [英] JavaScript & copy style

查看:102
本文介绍了JavaScript&复制风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javascript复制表格单元格。

I am copying a table cell with javascript.

它工作正常,只是它不复制样式。
我想复制如下,但是没有工作。
newCell.style = oldCell.style;

It works fine, just that it doesn't copy the style. I wanted to copy like below, but that didn't work. newCell.style=oldCell.style;

所以我想我的文本对齐,我必须这样复制:
newCell .style.textAlign = oldCell.style.textAlign;

So I figured that for my text-align, I have to copy it like this: newCell.style.textAlign=oldCell.style.textAlign;

这样有效,但是当我添加一个新的样式项时,我必须记住在这里注册它。

That worked, but whenever I add a new style item, I have to remember to register it here.

所以,我现在的问题是如何循环风格和复制每个项目在那里?

So, my problem now is how can I loop over the style and copy every item in there?

我设法这样做:

 var strAttribute = GetDomNameFromAttributeName(oRow.cells[1].style[0]);
    var styletocopy = eval('oRow.cells[1].style.'+strAttribute);
    eval("newCell.style."+strAttribute+"='"+styletocopy+"'"); // //newCell.style.textAlign='center';

但这不适用于IE。

有没有办法在IE中循环样式元素?

Is there any way to loop over the style elements in IE? Or is there any better way to copy all style elements?

推荐答案

eval('oRow.cells[1].style.'+strAttribute)

$ c> eval 这样(*)。在JavaScript中,您可以使用方括号访问名称存储在字符串中的属性。 object.plop object ['plop']相同

Never use eval like this(*). In JavaScript you can access a property whose name is stored in a string using square brackets. object.plop is the same as object['plop']:

to.style[name]= from.style[name];

(*:从不使用 eval


有什么方法可以循环使用样式元素

Is there any way to loop over the style elements

style 对象应支持 DOM第2级CSS CSSStyleDeclaration 界面。你可以循环规则,并将它们应用到另一个元素,例如:

The style object is supposed to support the DOM Level 2 CSS CSSStyleDeclaration interface. You could loop over the rules and apply them to another element like this:

for (var i= from.style.length; i-->0;) {
    var name= from.style[i];
    to.style.setProperty(name,
        from.style.getPropertyValue(name),
        priority= from.style.getPropertyPriority(name)
    );
}




$ b

in IE?

不,IE不支持整个CSSStyleDeclaration接口,上面的不会工作。但是有一个更简单的方法,不涉及循环,工作在IE和其他浏览器:

No, IE does not support the whole CSSStyleDeclaration interface and the above won't work. However there is a simpler way not involving looping that will work on IE and the other browsers too:

to.style.cssText= from.style.cssText;

很简单! IE不能完全保留CSS文本的方式,但它的区别对于简单的内联样式复制并不重要。

As simple as that! IE doesn't quite preserve the CSS text the way it should, but the difference doesn't matter for simple inline style copying.

然而,正如Pikrass所说的),如果你复制一个整个元素而不只是样式, cloneNode 是迄今为止最优雅的方式。

However, as Pikrass said (+1), if you are copying a whole element and not just the styles, cloneNode is by far the most elegant way to do that.

这篇关于JavaScript&复制风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆