顾名思义,innerhtml属性值代表html标记里的内容,即一个完整标记的内容。比如上例<div id="counter">点击的次数 = 0</div>中<div></div>里的内容“点击的次数 = 0”。
innerhtml属性也可以包含许多html 标记,例如:
<div id="counter2"><font color="red">点击的次数 = 0</font></div>
此时的innerhtml的内容为:<font color="red">点击的次数 = 0</font>
可以通过下面的方法进行刷新内容:
document.getelementbyid("counter2").innerhtml = "<font color='purple'>点击的次数 = " + hits + "</font>";
3.水平和垂直移动元素
编写dhtml代码最头疼的一件事情就是浏览器无关地在屏幕上移动元素,当我们提起元素水平位置和垂直位置时,自然会想到left和top,netscape navigator使用left和top属性,但internet explorer使用style的pixelleft和pixeltop属性,netscape 6则使用w3c规范的left和top属性,由于internet explorer 5以上版本的浏览器也支持此属性,因此,我们可以编写浏览器无关的水平移动元素的脚本代码:
<form>
<input id="counter1" style="position:relative; left:'0px'" type="button" value="移动按钮"
onclick="document.getelementbyid('counter1').style.left = '100px';">
</form>
单击上面的代码生成的按钮时,可以看到它移动到100px的位置,如果你不写上单位px,你不会出错,但那不是w3c/dom推荐使用的。
4.设定元素坐标值
设定和取得元素位置的浏览器无关w3c规范的办法是通过style元素的left和top属性来实现的,尽管这些属性被解释为物理计量单位,即字符串,这些字符串包含一个数字和一个“px”。我们在设定这些属性的时候,必须在数字的后面加上“px”。例如:给id="counter1"的元素设定水平位置为 xlocation,我们应当写:
document.getelementbyid('counter1').style.left = xlocation + "px";
如果不写“px”,浏览器也能识别。浏览器会认为计量单位是px,会自动加上它。但你要获取元素位置的时候,结果总是带"px" 的字符串。
document.getelementbyid('counter1').style.left = xlocation;
the browser assumes the unit of measure is pixels and will add the "px" automatically. you'll always get a "px"-ended string when querying the top and left properties.
记住left和top的返回值是很重要的,否则,你的浏览器会报告错误啊。如果你需要他们的数值时,可以使用parseint()方法,此方法把字符串从左到右转换成整数,当没有整数可以进行转换的时候,转换停止。例如:parseint("50px") 的结果是 50。下面的代码在你每按一次按钮的时候,按钮位置增加50px。
<form>
<input id="counter1" style="position:relative; left:'0px'" type="button"
value="移动按钮" onclick="handleclick()">
</form>
<script language="javascript">
<!--
var xlocation = parseint(document.getelementbyid('counter1').style.left);
function handleclick() {
xlocation += 50;
document.getelementbyid('counter1').style.left = xlocation + "px";
}
// -->
</script>
5.元素的可视性
要编写浏览器无关的设定和获取元素可视性的方法是采用w3c规范的推荐的style元素的visibility属性。visibility可以取以下三个值:
1."",即 空字符串
2."hidden"
3."visible"
当元素的visibility值为""或为"visible"时,元素在浏览器里是可见的,为"hidden"时,则不可见。要检测某元素的可视性,有两个办法:
if (visibility == "")...
或者:
if (visibility != "hidden")...
6.元素闪烁效果的实现
<blank>标记是netscape navigator特有的,netscape 6将会在以后取消这一标记。w3c规范推荐使用样式单style的text-decoration:blink来实现这一效果,但它只有netscape navigator 和 netscape 6支持,internet explorer仍旧不支持这一效果。下面的两行代码在netscape navigator 和 netscape 6里都会闪烁,
<blink>此行文字在netscape navigator 和 netscape 6应当闪烁</blink>