web-sys:DOM 你好世界

查看完整源代码在线查看编译后的示例

使用 web-sys,我们可以与所有标准的 Web 平台方法进行交互,包括 DOM 的方法!在这里,我们来看一个简单的“你好,世界!”,它在 Rust 中创建一个 DOM 元素,对其进行自定义,然后将其附加到页面。

Cargo.toml

你可以在这里看到我们如何依赖 web-sys 并激活相关功能来启用所有各种 API

[package]
authors = ["The wasm-bindgen Developers"]
edition = "2021"
name = "dom"
publish = false
version = "0.0.0"

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = { path = "../../" }

[dependencies.web-sys]
features = ['Document', 'Element', 'HtmlElement', 'Node', 'Window']
path = "../../crates/web-sys"

[lints]
workspace = true

src/lib.rs


# #![allow(unused_variables)]
#fn main() {
use wasm_bindgen::prelude::*;

// Called by our JS entry point to run the example
#[wasm_bindgen(start)]
fn run() -> Result<(), JsValue> {
    // Use `web_sys`'s global `window` function to get a handle on the global
    // window object.
    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");

    // Manufacture the element we're gonna append
    let val = document.create_element("p")?;
    val.set_text_content(Some("Hello from Rust!"));

    body.append_child(&val)?;

    Ok(())
}

#}