简体   繁体   English

如何读取 php 中 html 元素的 class 名称?

[英]How to read class name of a html element in php?

I am trying to make a project in php in which the class name will be read and transformed into variable and will set background of that specific color mentioned in the class.我正在尝试在 php 中创建一个项目,其中 class 名称将被读取并转换为变量,并将设置 class 中提到的特定颜色的背景。 for eg, if I type <div class="#999"> , I should get the background color #999 of the element (div).例如,如果我输入<div class="#999"> ,我应该得到元素 (div) 的背景颜色#999 I did everything fine but having trouble to get the element's class, pls help me out how to get the class of the element.我做的一切都很好,但无法获得元素的 class,请帮助我了解如何获得元素的 class。 Thanks in advance.提前致谢。

Just use the data- attribute and not the class name.只需使用 data- 属性而不是 class 名称。 In your case I would add data-bg="#999" and then read it in JS and set the background color.在你的情况下,我会添加data-bg="#999"然后在 JS 中读取它并设置背景颜色。

Here is some documentation for data- 这是一些数据文档-

 const container = document.getElementById('container'); container.style.backgroundColor = container.dataset.bg;
 <div id="container" data-bg="#999">lorem ipsum</div>

This seems like a job for CSS, rather than PHP or even JavaScript.这似乎是 CSS 的工作,而不是 PHP 甚至 JavaScript。

You can either你可以

a) set an inline style on the element itself defining the background colour (this is simple and quick but not the most maintainable or flexible in the long run): a)在定义背景颜色的元素本身上设置内联样式(这简单快捷,但从长远来看不是最可维护或最灵活的):

 <div style="background-color:#999">Div Contents Here</div>

OR或者

b) define a CSS class which has a rule setting the background colour for all elements which have that class: b) 定义一个 CSS class 的规则,该规则为所有具有该 class 的元素设置背景颜色:

 .classA { background-color:#999; }
 <div class="classA">Div Contents Here</div>

This seems like the most efficient way to define a background colour.这似乎是定义背景颜色的最有效方法。 If you need to vary which colour the div is given, define multiple classes which have different background colours, and get your PHP to output a different class name for the div, depending on your rules.如果您需要更改 div 的颜色,请定义多个具有不同背景颜色的类,并根据您的规则 div 名称将 PHP 到 output 使用不同的 class 名称。

(NB Your question wasn't 100% clear so if I've misunderstood what you mean, then please let me know and I can update the answer.) (注意您的问题不是 100% 清楚,所以如果我误解了您的意思,请告诉我,我可以更新答案。)

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

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