简体   繁体   English

定义和访问HTML元素的costum属性

[英]Defining and accessing costum properties of an HTML-element

In a web project, technical business-related values have to be attached to specific elements. 在Web项目中,必须将与业务相关的技术价值附加到特定元素上。 Based on those values, decisions are to be made on the client side. 基于这些值,应在客户端进行决策。 One big advantage of this approach, were it possible, is that CSSs in my case are automatically generated from other formats (provided by the management). 如果可能的话,这种方法的一大优势是CSS是由其他格式自动生成的(由管理人员提供)。

I am trying to add my own properties to some CSS classes. 我正在尝试将自己的属性添加到一些CSS类中。 I have a css class like: 我有一个CSS类,如:

.className{
SomeProp: ThisIsTheValue;
}

In Javascript, I need to access this value. 在Javascript中,我需要访问此值。 I tried things like: 我尝试过类似的事情:

myVar.SomeProp
myVar["SomeProp"]

All returned null. 全部返回null。 Is there a way I can just read this value? 有没有办法我可以读取此值? Is that possible to add my own CSS properties? 是否可以添加我自己的CSS属性?

You can use the getComputedStyle() method in standard JavaScript: 您可以在标准JavaScript中使用getComputedStyle()方法:

Example

var element = document.getElementById('name'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');

You can use the top variable however you please, such as in the example it outputs in an alert. 您可以随意使用top变量,例如在警报中输出的示例中。

SomeProp is not a valid css property. SomeProp不是有效的css属性。 Use a different approach to achieve what you are trying to accomplish. 使用不同的方法来实现您要完成的任务。


The value can be stored at css as JSON , within css comment. 该值可以在css注释中以JSON形式存储在css Parse the .textContent of style element to retrieve value as javascript object. 解析style元素的.textContent ,以将值作为javascript对象检索。

 /*{"className":{"SomeProp": "ThisIsTheValue"}}*/ 
 <script> var styles = document.styleSheets[0].ownerNode; var obj = JSON.parse( styles.textContent .match(/(\\/\\*{.*})(?=\\*\\/)/)[0] .replace(/[/*]/g, "") .trim() ); console.log(obj["className"]["SomeProp"]) </script> 


You can't do this through CSS. 您无法通过CSS执行此操作。 The browser will only read the CSS properies that it knows and ignore the rest. 浏览器将仅读取其知道的CSS属性,而忽略其余属性。 You can't read them from JavaScript in any practical way. 您无法以任何实用的方式从JavaScript读取它们。 And you shouldn't, because CSS if for styling, not for business logic. 而且您不应该这样做,因为CSS只是用于样式设计,而不是用于业务逻辑。

You can however use custom HTML attributes. 但是,您可以使用自定义HTML属性。 Using data*-attributes you can store extra information in an HTML element and read it from JavaScript to use it in any way you like. 使用data *属性,您可以将额外的信息存储在HTML元素中,并从JavaScript读取信息,以便以自己喜欢的任何方式使用它。 Mozilla has some good documentation on the subject. Mozilla在这个问题上有一些很好的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM