Introduction to Text and Fonts
出自OpenFace
第八章 文本介绍
第二部分 教程介绍
目录 |
简介
此教程说明如何在lzx应用中使用text,在之后的16章中有对text的解释。
<text>标签
输入文字很简单,使用<text>标签
Example 8.1. 简单<text>标签
<canvas height="100" width="500" > <text> Hello, World! </text> </canvas>
文字被放在tag标签的中间,意味着字体的前后空白被忽略,如果在字体之前存在多个空格,显示的时候只有一个空格。如果中间存在换行,将只被当成一个空白元素。
<text>标签也是一个view,因此可以象view标签一样对待。它可以得到所有缺省的view属性,如width,x,y等等。
Example 8.2. <text> 是一个视图
<canvas height="100" width="500"> <text x="15" y="20" width="150"> Hello, World! We would like to welcome you to the launch of the OpenLaszlo Server. </text> </canvas>
注意为什么字体的显示被截断,因为我们设置了宽度属性?
多行文本
使文字自动换行一样非常简单,我们只需要把multiline属性设置成true:
Example 8.3. 多行文本
<canvas height="100" width="500"> <text x="15" y="20" width="150" multiline="true"> Hello, World! We would like to welcome you to the launch of the OpenLaszlo Server. </text> </canvas>
text仍遵循同样的规则,在这种情况下,文本被包裹在150px内(因为我们明确设置<text>标签的宽度,并按设置的大小自动换行)。
改变文本
<text>元素有两个函数来读和写它的内容:
getText()
setText()
getText()函数返回文字框中的内容,setText()函数采用字符串为参数来设置字体中的内容:
Example 8.4. 对文本进行读写
<canvas height="135" width="700">
<text x="15" y="15" oninit="Debug.write(canvas.theField.getText());">
Get Text
</text>
<text x="100" y="15" oninit="canvas.theField.setText('Hello, Laszlo!');">
Set Text
</text>
<text x="180" y="115" oninit="addText();">
Add Text
</text>
<script>
function addText() {
var origText = canvas.theField.getText();
var newText = origText + " And on.";
canvas.theField.setText(newText);
}
</script>
<text x="45" y="60" width="150" height="75" multiline="true" name="theField">Some sample text.</text>
</canvas>
使用这两个函数,非常容易的像字符串一样对它进行操作。
使用text时 记住<text/> 标签中的内容都可先由 getText()方法得到 是很重要的。
Example 8.5. 得到文本内容
<canvas height="135" width="700">
<script>
function writeOutBit() {
var myText = canvas.theField.getText();
Debug.write(myText);
}
</script>
<text x="15" y="15" oninit="writeOutBit();">
Write part of line
</text>
<text x="45" y="60" width="150" height="75" multiline="true" name="theField"/>
</canvas>
输入文本
使用<inputtext>标签这种简单的方式为用户提供一个文本区域。
Example 8.6. 使用 <inputtext>
<canvas height="135" width="700"> <inputtext name="myText" x="10" y="15">Enter text here</inputtext> <text x="45" y="45" oninit="Debug.writ(canvas.myText.getText());"> Write out text </text> </canvas>
inputtext>区域并没有迹象表明可以编辑和输入,当该区域得到焦点时,会有一个输入光标.<inputtext>元素可以接受所有<text>的属性。
Example 8.7. <inputtext> 接受 <text> 属性
<canvas height="100" width="500"> <inputtext name="myText" x="10" y="15" fontsize="12" width="100" height="50" multiline="true"> Enter very large quantities of text here. </inputtext> </canvas>
getText和setText函数同样可应用于<inputtext>上。

