javascript - 使用原型(prototype)javascript设置标题样式

标签 javascript html css prototype

我正在尝试使用原型(prototype)创建 H2 标题,以便可以根据需要单独设置它们。

我正在使用 this.appendChild(document.createTextNode('')); 将文本添加到 H2。我需要在 appendChild 之前使用父节点,我相信在这种情况下是 this 关键字,但我不确定它是否被识别为父节点或者它是否确实是 parent ?我也不确定如何通过构造函数本身的参数添加文本。我使用了一个变量“字体”,但不确定如何让它工作,因为它没有添加 css 样式?

我正在学习如何使用原型(prototype),所以如果我遗漏了任何其他明显的错误,请告诉我。

<div id='body'>
<div id='inner'>div here</div>
</div>
<script>
Heading.prototype.font;
Heading.prototype.color;
Heading.prototype.fontSize;
Heading.prototype.headingTxt;
Heading.prototype.setHeading = function() {

   var inner = document.getElementById('inner');
   this.headingTxt = document.createElement('h2');
   this.headingTxt.font = this.appendChild(document.createTextNode(''));
   this.headingTxt.style.color = this.color;
   this.headingTxt.style.fontSize = this.fontSize;
inner.appendChild(headingTxt);
}

function Heading(font, color, fontSize) {

   this.font = font;
   this.color = color;
   this.fontSize = fontSize;
}

var title = new Heading('heading here', 'red', 20);
title.setHeading();

</script>

谁能帮我解决这个问题?

最佳答案

这是我精简的工作版本:

function Heading(font, color, fontSize) {
   this.font = font;
   this.color = color;
   this.fontSize = fontSize;
}

Heading.prototype.setHeading = function() {
   var inner = document.getElementById('header'); //make sure inner exists
   this.headingTxt = document.createElement('h2'); //you could also scope this to be local with var if you want it to be private 
   inner.appendChild(this.headingTxt);
}

var title = new Heading('heading here', 'red');
title.setHeading();

关于javascript - 使用原型(prototype)javascript设置标题样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689177/

相关文章:

javascript - 如何使用react-router渲染嵌套组件

javascript - 我需要将表格中的数据提取到 JavaScript 图表中

html - 如何制作 HTML/CSS/JS 变色背景(就像 Kahoot.it 有的那样)

css - 两个div并排-一个在最左边,另一个在中间

javascript - 如何解析多个数组的数组

javascript - 如何更改移动设备上 HTML5 视频的播放速度?

javascript - Web Audio API - 录制到 MP3?

html - 百分比宽度 Div 不适合

css - 背景图像:封面,闪烁的图像

css - 初始颜色...它是如何工作的?