javascript - 如何将所有计算样式设置为元素上的文字样式?
问题描述
这个问题与 SO 上的这个问题类似(我认为):How to move all computed CSS styles from a element and apply them to another 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>
推荐阅读
- php - 当新用户未出现在 phpmyadmin 数据库中时,php 中的注册过程成功完成
- regex - 带变量的 awk 处理
- php - json没有被php接收
- javascript - React-snapshot 使用 create-react-app 和 serve 在所有路由上预渲染 index.html
- powershell - 如何使用 powershell 更改任务触发器?
- c - Atmel:中断后无法转主
- firebase - 在从云 Firestore 数据库中检索主图像之前,如何在 CircleAvatar 中放置虚拟图像?
- ios - Xcode IDE 布局未与 Main.storyboard 一起显示 ViewController 连接
- php - 降低子数组键并组合项目
- java - 使用gradle在eclipse中导入spring boot应用