javascript - 在html中调用js方法

标签 javascript html

我对 js 中的类以及如何在 html 文件中调用它有疑问。

class SetProp(){
  constructor(height,width){
    this.height = height;
    this.width = width;
  }
  function getHeight(){
    return this.height;
  }
  function getWidth(){
    return this.width;
  }
}
<!DOCTYPE html>
<html>
  <head>
    <title>Hello</title>
    <script src="TryClass.js" type="text/javascript">
      prop = new SetProp(1000,1000);
    </script>
  </head>
  <body>
    <h1>Hello</h1>
    <canvas id="canvas" width="prop.getWidth() " height="prop.getHeight();" style="border:1px solid #000000"></canvas>
  </body>
</html>

我想用这个方法制作 1000*1000 的 Canvas 。 并且需要练习使用类。

最佳答案

html 属性 widthheight 不能分配给函数,你需要做的是编写一个函数,在按钮点击时或之后返回宽度和高度DOM 加载使用选择器使用 Javascript 修改元素的属性,如下所示:

document.getElementById('canvas').style.width =prop.getWidth() ;
document.getElementById('canvas').style.height =prop.getHeight() ;

关于javascript - 在html中调用js方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319336/

相关文章:

html - CSS 100% 宽度大于 100%

javascript - 如何使用与下拉列表中选择的值不同的值

javascript - 定义未定义 Javascript Node

javascript - 调用函数并忽略回调参数

javascript - 定时文本交换?

javascript - 单击列表项后显示子列表

html - 如何获取 ContentEditable 区域的行数和当前插入符行的位置?

JavaScript:定位动态创建的元素,以便 "floats"位于页面上

用于在图像底部放置标签的 HTML

html - 如何使用CSS添加垂直渐变?