|           编程(Programming)是编定程序的中文简称,就是让计算机代码解决某个问题,对某个计算体系规定一定的运算方式,使计算体系按照该计算方式运行,并最终得到相应结果的过程。为了使计算机能够理解(understand)人的意图,人类就必须将需解决的问题的思路、方法和手段通过计算机能够理解的形式告诉计算机,使得计算机能够根据人的指令一步一步去工作,完成某种特定的任务。这种人和计算体系之间交流的过程就是编程。 【实例名称】 对联广告JS代码怎么写 【实例描述】 大型门户网站为了获取利益都提供了大量的广告。对联广告就是常用的具有中国特色的广告。本例学习制作对联广告。 【实例代码】 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" 
content="text/html; charset=gb2312" />
<title>-本站(www.xue51.com)</title>
 </head>
<body leftmargin="0" topmargin="0">
<script type="text/javascript">
var delta=0.115 
var collection; 
function floaters() 
{ 
this.items = []; 
//在页面中动态添加div,参数依次代表:div的id,x坐标,y坐标,显示的内容
this.addItem= function(id,x,y,content) 
{ 
document.write('<DIV id='+id+' style="Z-INDEX: 0; 
POSITION: absolute;width:80px; height:60px;
left:'+(typeof(x)=='string'?eval(x):x)+';
top:'+(typeof(y)=='string'?eval(y):y)+'">'+content+'</DIV>'); 
 var newItem= {}; 
newItem.object= document.getElementById(id); 
newItem.x= x; 
newItem.y= y; 
this.items[this.items.length]= newItem; 
} 
 this.play= function() 
{ 
collection = this.items 
setInterval('play()',10); 
} 
} 
//显示对联,此方法绑定到定时器
function play() 
{ 
if(screen.width<=800) 
{ //宽度小于800时,不显示对联
for(var i=0;i<collection.length;i++) 
{ 
collection[i].object.style.display = 'none'; 
} 
return; 
} 
for(var i=0;i<collection.length;i++) 
{ 
var followObj= collection[i].object; 
var followObj_x= (typeof(collection[i].x)==
'string'?eval(collection[i].x):collection[i].x); 
var followObj_y= (typeof(collection[i].y)==
'string'?eval(collection[i].y):collection[i].y); 
if(followObj.offsetLeft!=(document.body.scrollLeft+followObj_x)) { 
var dx=(document.body.scrollLeft+followObj_x-followObj.offsetLeft)*delta; 
dx=(dx>0?1:-1)*Math.ceil(Math.abs(dx)); 
followObj.style.left=followObj.offsetLeft+dx; 
} 
if(followObj.offsetTop!=(document.body.scrollTop+followObj_y)) { 
var dy=(document.body.scrollTop+followObj_y-followObj.offsetTop)*delta; 
dy=(dy>0?1:-1)*Math.ceil(Math.abs(dy)); 
followObj.style.top=followObj.offsetTop+dy; 
} 
followObj.style.display= ''; 
} 
}
var theFloaters= new floaters(); 
//创建悬浮对联广告
//添加2幅广告
theFloaters.addItem('div1','document.body.clientWidth-135',0,
'</a><br><a href=http://images.sohu.com/cs/music/070330_120-120.gif 
target="_blank"><img src=http://images.sohu.com/cs/music/070330_120-120.gif 
width="100" height="267" border="0" /></a>'); 
theFloaters.addItem('div2',20,0,'<br>
<a href="http://images.sohu.com/cs/music/070330_120-120.gif" target="_blank">
<img src="http://images.sohu.com/cs/music/070330_120-120.gif" width="100" 
height="267" border="0" /></a>'); 
theFloaters.play();  //显示
</script>
</body>
</html>
 
 【运行效果】   【难点剖析】 本例的重点是如何动态往页面中添加div,并在指定的位置显示。动态添加元素本例使用的是“document.write”方法,是最常用也是最简单的输出文本流的方法。关于位置的选取请参考本例的“Play”方法,其中使用了“eval”方法来实现字符串格式到数值格式的转换。 【源码下载】 为了JS代码的准确性,请点击:对联广告JS代码 进行本实例源码下载  
 使用编程语言写的程序,由于每条指令都对应计算机一个特定的基本动作,所以程序占用内存少、执行效率高。 
 |