javascript - 如何使用 javascript 获取自定义 css var 的内联样式

标签 javascript html css inline-styles

<分区>

如何从元素中获取自定义 CSS 变量的内联样式?
我可以轻松获取宽度或任何其他传统样式,但在尝试获取自定义内联样式时出现错误。有没有办法提取这种样式数据?预先感谢您提供的任何帮助。请不要使用 jQuery。

var styleDivWidth = document.getElementById('myId').style.width;
console.log(styleDivWidth);

/*
var styleDivRotation = document.getElementById('myId').style.--rotation;
console.log(styleDivRotation);
*/
.myClass{
background-color:red;
float:left;	
--rotation: 45deg;
transform: rotate(var(--rotation));
margin:20px;  
}
<div id="myId" class="myClass" style="width:100px; height:100px;
 --rotation:-45deg;">

最佳答案

您可以通过解析 cssText 属性来提取它。

下面是一些代码和 JsFiddle:

const cssText = document.getElementById('myId').style.cssText;
console.log(cssText);
const rotationProp = cssText.split("; ").find(style => style.includes("rotation"));
console.log(rotationProp);

const rotationValue =  rotationProp.slice(rotationProp.indexOf(":") + 1, rotationProp.indexOf(";"));
console.log(rotationValue);

JsFiddle:https://jsfiddle.net/2ajp1cug/

关于javascript - 如何使用 javascript 获取自定义 css var 的内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58735794/

相关文章:

html - 如何将 Font Awesome 图标向右对齐?

javascript - 尽管宽度为 :0;,但 Textarea 滚动条不会消失

javascript - JQuery 代码不工作

javascript - iPad 上的 Bootstrap 3 下拉列表无法正常工作

php登录表单和提交按钮

css - 让我的 CSS 转换工作的问题

html - 转换 CSS3 导航菜单

javascript - 使用 JQuery 隐藏 Kendo ui 命令列

javascript - 以 Angular 方式将工厂注入(inject) Controller 中

javascript - 在 jQuery 中合并对象