javascript - 如何将所有计算样式设置为元素上的文字样式?

标签 javascript jquery css styles

这个问题类似于(我认为)关于 SO 的这个问题:How to move all computed CSS styles from one element and apply them to a different element using JavaScript?

我想要做的是找到所有已通过 css 工作表应用的样式,并在元素上显式设置(如使用 style= 属性)。我想这样做的原因是,如果我在那里打开 MS Word (2010),它将选择样式

这是我的代码

var $this = $(this);
var styles = window.getComputedStyle(this, null);
$this.css(styles);

我也试过

var styles = document.defaultView.getComputedStyle(this, null);

当我在最后一行 ($this.css(styles) 周围放置一个 try catch 时,我收到一条错误消息“无效的调用对象”。我不明白这是什么问题

最佳答案

好吧,下面的代码片段可以满足您的需求,但我认为这不是您所需要的。 MS Word 不是浏览器,我不确定它是否支持所有样式或者 jQuery 是否在那里工作...

var $this = $('b');
var styles = window.getComputedStyle($this[0]);

$this.css(
  Object.values(styles).reduce(
    (a, e) => 0*(a[e] = styles[e]) || a, {}
  )
)

console.log(`style="${$this.attr('style')}"`)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b>I have styles</b>

关于javascript - 如何将所有计算样式设置为元素上的文字样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046925/

相关文章:

javascript - 如何使用ajax传递多个值?

jquery - Cakephp:使多个复选框表现得像单选按钮

html - Flex 元素在 Firefox 中溢出

css - 基于带有 js 库的容器宽度的字体缩放

javascript - 在 Javascript 中将 <br> 替换为 '\n' 时打印额外的新行

javascript - 等待一项发布完成后再开始另一项发布

javascript - 单击第二个按钮后,jQuery on click 开始正常工作

html - 具有不同高度列的 Bootstrap 行

javascript - 无法发送异步 POST 请求

javascript - 如何使 Bootstrap 仅在 Div 内运行?