在Vaadin中,如何在Label中设置样式而不影响整个页面

时间:2017-11-20 09:24:52

标签: java vaadin vaadin8

例如,我在plot中设置了以下html代码:

Label

上面代码的问题在于它将整个页面设置为Arial而不仅仅是Label label = new Label(); label.setContentMode(ContentMode.HTML); label.setValue("<style> * { font-size: 12px; font-family: Arial; } </style> hello world"); 。如果我使用Label,那么它只将样式设置为该组件,但无论出于何种原因,RichTextArea中定义的任何CSS样式都应用于整个页面......

仅供参考 - 如果您将Label设置为只读,则会得到完全相同的问题......

4 个答案:

答案 0 :(得分:4)

而不是添加内联样式。使用挂起Vaadin组件的addStyleName方法。

示例

<强>爪哇:

Label label = new Label();
label.addStyleName("my-custom-style");

<强> CSS:

.my-custom-style {
    font-size: 12px:
    font-family: Arial;
}

包含自定义StyleSheet。

  • @StyleSheet("my-style-sheet.css")添加到您的班级/用户界面
  • 的顶部
  • 在资源文件夹中的相同包结构下创建CSS文件。

修改

由于这是在生成的报告中使用而您无法使用上述解决方案:

而不是像你一样使用样式标签。如果将文本包装在span标记中,则可以使用内联样式将其专门应用于该Label:

label.setValue("<span style=\"font-size: 12px; font-family: Arial;\">Your text here</span>");

注意:请注意使用该方法。您正在开放潜在的HTML注入,并需要采取措施来防止这种情况发生。

答案 1 :(得分:3)

隔离HTML树中的某些元素实际上并不是Vaadin问题。在HTML5中解决此问题的一种方法是使用iframe srcdoc属性(或src="data:..."}。

以下是如何将其与Vaadin8一起使用的示例但请注意:一旦您在Label中处理HTML, 的责任就是引用/编码那里的所有内容正确 - 特别是,因为您提到,所有内容都来自用户!

// run with `spring run --watch <file>.groovy`
@Grapes([
@Grab('com.vaadin:vaadin-spring-boot-starter:2.0.1'),
@Grab('com.vaadin:vaadin-server:8.1.6'),
@Grab('com.vaadin:vaadin-client-compiled:8.1.6'),
])

import com.vaadin.ui.*
import com.vaadin.ui.themes.*
import com.vaadin.shared.*
import com.vaadin.shared.ui.ContentMode


@com.vaadin.spring.annotation.SpringUI
@com.vaadin.annotations.Theme("valo")
class MyUI extends UI {
        protected void init(com.vaadin.server.VaadinRequest request) {
        setContent(new VerticalLayout(
            new Label("<h1>Hello</h1><p>Lorem Ipsum</p>", ContentMode.HTML),
            new Label("""
                <iframe srcdoc="
                    <style type='text/css'>* { font-family: monospace; font-size: 36pt; background-color: green; }</style>
                    <h1>Test</h1>
                    <p>Lorem Ipsum</p>
                "></iframe>
            """, ContentMode.HTML),
            new Label("<h1>Hello</h1><p>Lorem Ipsum</p>", ContentMode.HTML),
        ))  
    }
}

答案 2 :(得分:1)

通常,您不应该为Vaadin组件添加内联样式。您应该在主题或自定义CSS文件中的CSS文件中添加样式定义,并将它们添加为@Jay。

如果你真的想使用内联样式定义,那么你必须使用CssLayout

https://vaadin.com/docs/v8/framework/layout/layout-csslayout.html

答案 3 :(得分:1)

我最终使用的是BrowserFrame。唯一的事情是BrowserFrame的高度不能像带有-1px的Label一样动态调整大小。