You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vaadin自定义Video类中定义play()和pause()方法

实现Vaadin自定义Video类的play()和pause()方法

要让自定义的Video类支持程序化调用播放和暂停,直接通过Vaadin的Element API调用HTML video元素的原生方法即可,无需额外复杂逻辑。

修改后的完整代码

@Tag("video")
public class Video extends Component implements ClickNotifier<Video> {

    protected String getVideoSourceAttributeName() {
        return VideoAttributes.Source;
    }

    public void setWidth(String width) {
        this.getElement().setAttribute(VideoAttributes.Width, width);
    }

    public void setHeight(String height) {
        this.getElement().setAttribute(VideoAttributes.Height, height);
    }

    // 新增播放方法:调用HTML video元素的原生play()方法
    public void play() {
        getElement().callJsFunction("play");
    }

    // 新增暂停方法:调用HTML video元素的原生pause()方法
    public void pause() {
        getElement().callJsFunction("pause");
    }

    private interface VideoAttributes {
        String Controls = "controls";
        String Source = "src";
        String CurrentTime = "currentTime";
        String AutoPlay = "autoplay";
        String Loop = "loop";
        String Preload = "preload";
        String Poster = "poster";
        String Width = "width";
        String Height = "height";
    }

    public interface functions {}
}

关键说明

  • callJsFunction("play") 和 callJsFunction("pause") 会直接向浏览器端的video DOM元素发送指令,调用其原生的播放/暂停方法,和直接操作HTML video元素的行为完全一致。
  • 同时修复了ClickNotifier的泛型声明,指定为ClickNotifier<Video>,避免编译警告。

内容的提问来源于stack exchange,提问作者Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:12:05