Docs

Documentation versions (currently viewingVaadin 24)
Documentation translations (currently viewingChinese)

此页面为官方文档(http://vaadin.com/docs)的机器翻译版本。页面可能包含错误、不准确或表述不当之处。Vaadin不对翻译的准确性、可靠性或及时性作出任何保证或声明。

使用Element API动态设置样式

如何使用动态类名或内联样式设置元素样式。

您可以使用[classname]Element API,通过动态类名或内联样式为元素设置样式。

Element API提供了两个方法帮助进行样式设置:

  • getClassList(): 获取元素使用的CSS类名集合

  • getStyle(): 获取用于管理元素内联样式的样式实例

修改元素上的CSS类

您可以使用[methodname]`getClassList()`方法来获取元素所使用的CSS类名集合。 返回的集合可用于添加或移除类名。

示例: CSS样式规则。

Source code
CSS
.blue {
  background: blue;
  color: white;
}

示例: 使用[methodname]`getClassList()`方法动态修改元素的类名。

Source code
Java
button.setText("Change to blue");
button.addEventListener("click",
    e -> button.getClassList().add("blue"));

示例: 使用`getClassList`方法添加和移除类名。

Source code
Java
element.getClassList().add("error");
element.getClassList().add("critical");
element.getClassList().remove("primary");

// 返回 "error critical".
element.getProperty("className");
  • element.getProperty("className") 方法获取包含所有类名的连接字符串。

不能直接使用[methodname]setProperty() 方法修改`classList`或`className` 属性。

可以使用以下方法设置和获取元素的`class`属性:

  • element.setAttribute("class", "foo bar"): 此操作会清空之前设置的任何`classList`属性。

  • element.getAttribute('class'): 此方法返回`classList`属性内容的单一连接字符串。

使用Style对象

可通过[methodname]element.getStyle()`方法返回的[classname]`Style`对象来为元素设置和移除内联样式。 样式属性名可使用驼峰命名法(例如,`backgroundColor)或短横线命名法(例如,background-color)。

示例:使用[methodname]`getStyle()`方法动态设置内联样式。

Source code
Java
Element input = ElementFactory.createInput();
button.setText("Change to the entered value");
button.addEventListener("click",
    e -> button.getStyle().set("background",
            input.getProperty("value")));

示例:使用[methodname]`element.getStyle()`方法设置和移除样式对象。

Source code
Java
element.getStyle().set("color", "red");
// 驼峰式命名
element.getStyle().set("fontWeight", "bold");
// 短横线式命名
element.getStyle().set("font-weight", "bold");

// 驼峰式命名移除属性
element.getStyle().remove("backgroundColor");
// 短横线式命名移除属性
element.getStyle().remove("background-color");

element.getStyle().has("cursor");

FCBB787F-B86D-44B1-AE23-0944E4F1D079