当前位置: 首页>>代码示例>>Scala>>正文


Scala document类代码示例

本文整理汇总了Scala中org.scalajs.dom.document的典型用法代码示例。如果您正苦于以下问题:Scala document类的具体用法?Scala document怎么用?Scala document使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了document类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: Statistics

//设置package包名称以及导入依赖的类
package ui

import org.scalajs.dom.document
import org.scalajs.dom.html.{Div, Element, Span}
import ui.helper.HtmlCreator

object Statistics {
  def setField[T](id: String, format: String)(value: Double): Unit = {
    Option(document.getElementById(id))
      .foreach(elem => {
        elem.textContent = format.format(value)
      })

  }

  def setAvgSpeed(avgSpeed: Double): Unit = setField("speed", "%8.5f")(avgSpeed)
  def setStdDev(stdDev: Double): Unit = setField("stddev", "%8.5f")(stdDev)
  def setIteration(iteration: Int): Unit = setField("iteration", "%5.0f")(iteration.toDouble)
  def setCount(vehiclesCount: Int, roadLength: Int): Unit = {
    setField("vehicles-count", "%5.0f")(vehiclesCount.toDouble)
    setField("road-count", "%5.0f")(roadLength.toDouble)
    setField("actual-density", "%5.4f")(vehiclesCount.toDouble / roadLength.toDouble)
  }

  def setupUI(): Element = {
    val container = HtmlCreator.create[Div]("statistics-box")
    container.classList.add("jumbotron")
    container.appendChild(StatBox.createStat("road-count", "Liczba komórek drogi: "))
    container.appendChild(StatBox.createStat("vehicles-count", "Liczba pojazdów: "))
    container.appendChild(StatBox.createStat("actual-density", "Faktyczna g?sto?? pojazdów: "))
    container.appendChild(StatBox.createStat("speed", "?rednia pr?dko??: "))
    container.appendChild(StatBox.createStat("stddev", "Odchylenie standardowe pr?dko?ci: "))
    container.appendChild(StatBox.createStat("iteration", "Iteracja: "))

    container
  }

  object StatBox {
    def createStat(valueName: String, constantText: String): Div = {
      val box = HtmlCreator.create[Div](valueName + "-box")
      val textSpan = HtmlCreator.create[Span]("text-" + valueName)
      textSpan.classList.add("label")
      textSpan.classList.add("label-info")
      textSpan.textContent = constantText
      box.appendChild(textSpan)

      val valueSpan = HtmlCreator.create[Span](valueName)
      valueSpan.textContent = "0"
      box.appendChild(valueSpan)

      box
    }
  }
} 
开发者ID:tlewowski,项目名称:nagel-schreckenberg,代码行数:55,代码来源:Statistics.scala

示例2: Road

//设置package包名称以及导入依赖的类
package ui

import org.scalajs.dom.html.{Div, Element}
import org.scalajs.dom.{CanvasRenderingContext2D, document, html}
import ui.helper.HtmlCreator

object Road {
  val cellCountPerRow = 150
  val cellSizeInPixels = 5

  def setupUI(): Element = {

    val roadBox = HtmlCreator.create[Div]("simulation-box")

    val simulationCanvas = document.createElement("canvas")
    simulationCanvas.id = "simulation-canvas"
    simulationCanvas.setAttribute("width", cellCountPerRow * cellSizeInPixels + "px")

    roadBox.appendChild(simulationCanvas)

    roadBox
  }

  def draw(road: Vector[Option[Int]]): Unit = {
    val rows = road.length / cellCountPerRow
    val canvas = document.getElementById("simulation-canvas").asInstanceOf[html.Canvas]
    val ctx = canvas.getContext("2d").asInstanceOf[CanvasRenderingContext2D]
    canvas.width = cellCountPerRow * cellSizeInPixels
    canvas.height = rows * cellSizeInPixels
    ctx.strokeStyle = "red"
    ctx.lineWidth = 20

    road.zipWithIndex.foreach(r => {
      if (r._1.isDefined) {
        ctx.fillRect(cellSizeInPixels*(r._2 % cellCountPerRow), cellSizeInPixels*(r._2 / cellCountPerRow), cellSizeInPixels, cellSizeInPixels)
      }
      else {
        ctx.clearRect(cellSizeInPixels*(r._2 % cellCountPerRow), cellSizeInPixels*(r._2 / cellCountPerRow), cellSizeInPixels, cellSizeInPixels)
      }
    })

    ctx.stroke
  }
} 
开发者ID:tlewowski,项目名称:nagel-schreckenberg,代码行数:45,代码来源:Road.scala

示例3: ConfigurationBox

//设置package包名称以及导入依赖的类
package ui

import org.scalajs.dom.{Element, document}

object ConfigurationBox {
  def create(triggerCallback: SimulationTrigger => Unit): Element = {
    val configBox = document.createElement("form")
    configBox.id = "params-box"
    configBox.appendChild(WidthBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(DensityBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(ProbabilityBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(SpeedBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(SpeedStepBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(MinimumTimeoutBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(CountedIterationsBox.setupUI(SimulationTriggeringButtons))
    configBox.appendChild(SimulationTriggeringButtons.setupUI(triggerCallback))

    configBox
  }
} 
开发者ID:tlewowski,项目名称:nagel-schreckenberg,代码行数:21,代码来源:ConfigurationBox.scala

示例4: Images

//设置package包名称以及导入依赖的类
package net.xylophones.frogger

import org.scalajs.dom.document

object Images {

  private val mediaPath = document.getElementById("frogger").getAttribute("mediaPath")
  
  private def fullPath(pth: String) = s"$mediaPath$pth"

  val tiles = new TiledImage(Image(fullPath("img/tiles.png")), 32, 32)
  val top = Image(fullPath("img/top.png"))
  val oneUp = Image(fullPath("img/1_up.png"))
  val highScore = Image(fullPath("img/high_score.png"))
  val nums = Image(fullPath("img/numbers.png"))
  val lifeImage = Image(fullPath("img/life.png"))
  val levelImage = Image(fullPath("img/level2.png"))
  val timeImage = Image(fullPath("img/time.png"))
  val frog = Image(fullPath("img/frog.png"))
  val deadFrog = Image(fullPath("img/deadfrog.png"))

} 
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:23,代码来源:Images.scala

示例5: App

//设置package包名称以及导入依赖的类
package net.xylophones.frogger

import org.scalajs.dom
import org.scalajs.dom.document
import org.scalajs.dom.html.{Canvas}

import scala.scalajs.js.JSApp
import scala.scalajs.js.timers._

object App extends JSApp {
  private val canvas = document.getElementById("frogger").asInstanceOf[Canvas]
  val ctx = canvas.getContext("2d").asInstanceOf[dom.CanvasRenderingContext2D]
  private val mediaPath = canvas.getAttribute("mediaPath")
  private val soundPlayer = new SoundPlayer(mediaPath)

  def main(): Unit = {
    addCanvas()
    val m = Layers.initialModel()
    loop(model = m)
  }

  def loop(lastTime: Long = System.currentTimeMillis, model: Model): Unit = {
    draw(model)

    val interval: Long = System.currentTimeMillis() - lastTime
    val desiredPause = 1000 / 25
    val pause = Math.max(0, desiredPause - interval)

    setTimeout(pause) {
      val newModel: Model = updateModel(model)

      loop(System.currentTimeMillis(), newModel)
    }
  }

  private def updateModel(model: Model): Model = {
    val newModel = ModelUpdaters.updaters.foldLeft(model) {
      (updatedModel: Model, updater: ModelUpdater) => updater.updateIfApplicable(updatedModel)
    }

    for (s <- newModel.sounds) {soundPlayer.play(s)}

    newModel.copy(sounds = Seq())
  }

  def draw(model: Model) = {
    (model.layers.all zip model.positions).foreach { case (l, p) => l.draw(ctx, p, model) }

    model.layers.frogLayer.draw(ctx, model.frogPosition, model)
  }

  def addCanvas(): Unit = {
    canvas.width = Config.gameWidth
    canvas.height = Config.gameHeight
  }
} 
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:57,代码来源:App.scala

示例6: Cookies

//设置package包名称以及导入依赖的类
package codes.mark.geilematte.facades

import org.scalajs.dom.document

import scala.scalajs.js.Date
import scalaz.std.list._

object Cookies {

  def read: Map[String, String] =
    document.cookie
      .split(";")
      .toList
      .map(_.split("=").toList)
      .flatMap(x =>
        (x.headOption, x.drop(1).headOption) match {
          case (Some(k), Some(v)) => List((k.trim, v))
          case _                  => Nil
        })
      .toMap

  def write(values:Map[String, String]): Unit = {
    val expiry = new Date(2020, 1)
    values.toList.foreach {
        case (k, v) =>
          val expires = expiry.toUTCString
          document.cookie = s"$k=$v;expires=$expires;path=/"
    }
  }
} 
开发者ID:i-am-the-slime,项目名称:geilematte,代码行数:31,代码来源:Cookies.scala

示例7: Context

//设置package包名称以及导入依赖的类
package org.codeape.sc.frontend

import io.udash._
import io.udash.wrappers.jquery._
import org.codeape.sc.shared.MainServerREST
import org.scalajs.dom
import org.scalajs.dom.{Element, document}

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scala.util.Try

object Context {
  implicit val executionContext = scalajs.concurrent.JSExecutionContext.Implicits.queue
  private val routingRegistry = new RoutingRegistryDef
  private val viewPresenterRegistry = new StatesToViewPresenterDef

  implicit val applicationInstance = new Application[RoutingState](routingRegistry, viewPresenterRegistry, RootState)

  import io.udash.rest._
  val port = Try(dom.window.location.port.toInt).getOrElse(80)
  val host = dom.window.location.hostname
  val restServer = DefaultServerREST[MainServerREST](host, port, "/api/")
}

object Init extends JSApp with StrictLogging {
  import Context._

  @JSExport
  override def main(): Unit = {
    logger.info("StampClock started")
    jQ(document).ready((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check your index.html file!")
      } else {
        applicationInstance.run(appRoot.get)
      }
    })
  }
} 
开发者ID:codeape,项目名称:StampClock,代码行数:42,代码来源:init.scala

示例8: ScalaJSExamples

//设置package包名称以及导入依赖的类
package com.outr.nextui.examples.browser

import com.outr.nextui.browser.ScalaJS
import com.outr.nextui.examples.Examples
import org.scalajs.dom.{Event, document, html}

import scala.scalajs.js.JSApp

object ScalaJSExamples extends JSApp {
  override def main(): Unit = {
    val div = document.createElement("div").asInstanceOf[html.Div]
    Examples().foreach { ui =>
      val a = document.createElement("a").asInstanceOf[html.Anchor]
      a.href = "#"
      a.addEventListener("click", {(evt: Event) =>
        document.body.removeChild(div)
        ScalaJS(ui)
      }, true)
      a.textContent = ui.name
      val p = document.createElement("p").asInstanceOf[html.Paragraph]
      p.appendChild(a)
      div.appendChild(p)
    }
    document.body.appendChild(div)
  }
} 
开发者ID:outr,项目名称:nextui,代码行数:27,代码来源:ScalaJSExamples.scala

示例9: Init

//设置package包名称以及导入依赖的类
package com.oni.udash

import acyclic.file

import io.udash._
import io.udash.wrappers.jquery._
import org.scalajs.dom.{ Element, document }

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scalacss.Defaults._
import scalacss.ScalatagsCss._
import scalatags.JsDom._
import com.oni.udash.styles._
import com.oni.udash.styles.OniStyles2
import com.oni.udash.styles.GlobalStyles
import com.oni.udash.styles.DemoStyles
import com.oni.udash.styles.partials.FooterStyles
import com.oni.udash.styles.partials.HeaderStyles
import org.scalajs.dom.raw.HTMLStyleElement

object Init extends JSApp with StrictLogging {
  import Context._

  @JSExport
  override def main(): Unit = {
    jQ(document).ready((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check your index.html file!")
      } else {
        applicationInstance.run(appRoot.get)

        jQ(GlobalStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(DemoStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(OniStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(OniStyles2.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(CsStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(CsStyles2.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(FooterStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
        jQ(HeaderStyles.render[TypedTag[HTMLStyleElement]].render).insertBefore(appRoot.get)
      }
    })
  }
} 
开发者ID:ObjectNirvana,项目名称:oni-web,代码行数:46,代码来源:init.scala

示例10: TutorialApp

//设置package包名称以及导入依赖的类
package jp.ne.opt.client

import jp.ne.opt.domain.TodoStore

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import japgolly.scalajs.react.{ReactComponentB, ReactDOM}
import japgolly.scalajs.react.vdom.prefix_<^._
import org.scalajs.dom.document

object TutorialApp extends JSApp {
  def main(): Unit = {
    println("helloWorld")
  }

  @JSExport
  def count():Unit = {
    countNumber +=1
    println(countNumber)
  }
  var countNumber: Int = 1

  val Hello =
    ReactComponentB[String]("Hello")
      .render_P(name => <.div(^.id:="hoge","Hello there ", name))
      .build

  ReactDOM.render(Hello("hohohohoho"), document.getElementById("content"))
} 
开发者ID:opt-tech,项目名称:scalajs-react-todo,代码行数:30,代码来源:Main.scala

示例11: GoogleSearchBox

//设置package包名称以及导入依赖的类
package net.scalytica.blaargh.components

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import org.scalajs.dom.document


object GoogleSearchBox {

  class Backend($: BackendScope[Unit, Unit]) {

    def scriptGen() = {
      val cx = "007449460818485879211:oyngikjfvr0"
      val googleScript = {
        val scr = document.createElement("script")
        scr.setAttribute("type", "text/javascript")
        scr.setAttribute("async", "true")
        scr.setAttribute("src", s"${document.location.protocol}//cse.google.com/cse.js?cx=$cx")
        scr
      }

      val s = document.getElementsByTagName("script")(0)
      s.parentNode.insertBefore(googleScript, s)
    }

    def render() = {
      <.div(^.dangerouslySetInnerHtml("<gcse:search></gcse:search>"))
    }
  }

  val component = ReactComponentB[Unit]("GoogleSearchBox")
    .stateless
    .renderBackend[Backend]
    .componentWillMount($ => Callback($.backend.scriptGen()))
    .buildU


  def apply() = component()

} 
开发者ID:kpmeen,项目名称:blaargh,代码行数:41,代码来源:GoogleSearchBox.scala

示例12: SampleApp1

//设置package包名称以及导入依赖的类
package se.ta

import scala.concurrent.duration._
import scala.scalajs.js.JSApp

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable
import org.scalajs.dom.document

object SampleApp1 extends JSApp {

  def viewTick(tick: Long) =
    <.div(
      <.p(s"Tick: $tick seconds")
    )

  val Tick =
    ReactComponentB[Long]("Tick")
      .render_P(tick => viewTick(tick))
      .build

  def main(): Unit = {

    println("Starting counting  10 ticks")

    Observable.interval(1 second)
      .doOnNext(x => ReactDOM.render(Tick(x), document.body))
      .take(10)
      .dump("0")
      .subscribe()
  }
} 
开发者ID:ThomasAlexandre,项目名称:scalajs-elm,代码行数:35,代码来源:SampleApp1.scala

示例13: Main

//设置package包名称以及导入依赖的类
package helloBinding

import com.thoughtworks.binding.Binding.{Var, Vars}
import com.thoughtworks.binding.dom
import org.scalajs.dom.raw.Event
import org.scalajs.dom.html.Input
import org.scalajs.dom.document


object Main extends scalajs.js.JSApp {

  @dom
  def render = {
    val name = Var("Binding.scala")
    val show = Var(false)
    <div>
      <p>
        <input type="checkbox" id="showCheckbox" onchange={_: Event => show := showCheckbox.checked }/>
        <label for="showCheckbox">
          Say hello to <input id="nameInput" value={name.get} oninput={_: Event => name := nameInput.value}/>
        </label>
      </p>
      {
        if (show.bind) {
          <p>
            Hello, {name.bind}!
          </p>
        } else {
          <!-- Don't show hello. -->
        }
      }
    </div>
  }

  def main(): Unit = {
    dom.render(document.body, render)
  }
} 
开发者ID:ThoughtWorksInc,项目名称:Binding.scala-activator-template,代码行数:39,代码来源:Main.scala

示例14: Main

//设置package包名称以及导入依赖的类
package com.github.aafa.vending

import com.github.aafa.vending.diode._
import org.scalajs.dom.{Node, document}

import scala.scalajs.js.JSApp
import scalatags.JsDom.all._

object Main extends JSApp {
  AppCircuit.subscribe(AppCircuit.zoom(a => a))(_ => render())

  def main(): Unit = {
    render()
  }

  private def render() = {
    document.body.innerHTML = ""
    content(document.body)
  }

  def content(targetNode: Node): Unit = {
    val insertCoin = button(`class` := "insertCoin", onclick := { () => AppCircuit(InsertCoin(CandyCoin(1))) }, ">> Insert CandyCoin here <<")
    val candies = AppCircuit.zoom(_.listOfCandies).value
    val coinsSlot = AppCircuit.zoom(_.coinsSlot).value.value
    val getTheCandy = AppCircuit.zoom(_.getTheCandySlot).value.map(_.name)
    val info = AppCircuit.zoom(_.machineInfo).value

    targetNode.appendChild(
      div(`class` := "container",
        h2("Candies for everyone!"),
        div(info),
        div(insertCoin),
        div(coinsSlot + " coins"),
        ul(`class` := "candyList",
          candies map (c => div(
            button(`class` := "candy", onclick := { () => AppCircuit(PurchaseCandy(c.candy)) },
              s"Purchase ${c.candy.name} for ${c.price.value}cc, only ${c.quantity} left")))
        ),
        div(`class` := "footer",
          button(
            `class` := "get-candy-slot", onclick := { () => AppCircuit(CandyTakenFromSlot) },
            getTheCandy
          )
        )
      ).render
    )

  }
} 
开发者ID:aafa,项目名称:vending,代码行数:50,代码来源:Main.scala

示例15: DoiApp

//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.gui

import scala.scalajs.js.JSApp
import org.scalajs.dom.document
import se.lu.nateko.cp.doi.gui.views.MainView

object DoiApp extends JSApp {

	val initState = DoiState(
		prefix = "10.5072",//test value; the actual one is fetched from backend
		dois = Nil,
		info = Map.empty,
		selected = None,
		ioState = IoState(None, None),
		alreadyExists = None,
		error = None
	)
	val store = new DoiRedux.Store(DoiReducer.reducer, initState)

	val mainView = new MainView(store)
	val renderer = new Renderer(mainView)
	store.subscribe(renderer)

	def main(): Unit = {
		val mainDiv = document.getElementById("main")
		mainDiv.parentNode.replaceChild(mainView.element.render, mainDiv)

		store.dispatch(ThunkActions.FetchDoiPrefix)
		store.dispatch(ThunkActions.DoiListRefreshRequest)
	}

} 
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:33,代码来源:DoiApp.scala


注:本文中的org.scalajs.dom.document类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。