https://github.com/gopherjs/gopherjs
A compiler from Go to JavaScript for running Go code in a browser
让你的golang代码在浏览器中执行(Golang转JavaScript)
gopherjs应用
最简单例子(accessing native javascript apis in go code)
写一个golang文件,姑且命名为main.go:
package main
import “github.com/gopherjs/gopherjs/js”
func main() {
js.Global.Get(“document”).Call(“write”, “Hello world!”)
}
运行命令行:
gopherjs build main.go -o demo.js
此时,生成了两个文件demo.js和demo.js.map。
新建一个html文件,姑且命名为test.html,键入:
<!doctype html>
打开test.html,查看结果。
操作DOM(honnef.co/go/js/dom)
github地址:
https://github.com/dominikh/go-js-dom
获取:
go get honnef.co/go/js/dom
浏览器播放mp3音频
main.go
package main
import “honnef.co/go/js/dom”
func main() {
d := dom.GetWindow().Document()
foo := d.GetElementByID("foo").(*dom.HTMLButtonElement)
foo.AddEventListener("click", false, func(event dom.Event) {
a := d.GetElementByID("audio").(*dom.HTMLAudioElement)
a.Play()
}) } ` 编译: gopherjs build main.go -o demo.js
test.html
<!doctype html>
Create and Append Element
main.go
package main
import “honnef.co/go/js/dom”
func main() {
d := dom.GetWindow().Document()
foo := d.GetElementByID("foo").(*dom.HTMLDivElement)
foo.AddEventListener("click", false, func(event dom.Event) {
div := d.CreateElement("div").(*dom.HTMLDivElement)
div.Style().SetProperty("color", "red", "")
div.SetTextContent("I am new div")
foo.AppendChild(div)
}) } 编译: gopherjs build append.go -o demo.js
test.html
<!doctype html>
更多例子
https://siongui.github.io/2016/01/10/gopherjs-dom-example-getElementById-innerHTML/
https://studygolang.com/articles/17838