二、DOM同JAVASCRIPT相结合,实例——拖拽和褪色技术
例1. 页面中拖拽效果的实现
可拖放DOM模式(Draggable DOM pattern)可以让用户在Web页面中对各个部分进行编辑,即只需要选中要移动的部分,将其拖拽到新的位置上,就可以重新安排整个页面的布局效果。
新建页面main.html,代码如下:
<!DOCTYPE html PUBLIC "-//W3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript" src="dom-drag.js"></script>
<link rel="stylesheet" href="style.css">
<title>Insert title here</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<div id="news_root" style="LEFT:20px;TOP:20px" class="root">
<div id="news_handle" class="handle">
定制窗口
<span style="TEXT-ALIGN:right"></span>
</div>
<div id="news" class="text">
欢迎使用拖拽功能
</div>
</div>
</form>
<script language="javascript">
//获得id为news_handle的element
var news_handle = document.getElementById("news_handle");
//获得id为news_root的element
var news_root = document.getElementById("news_root");
Drag.init(news_handle,news_root);
news.style.backgroundColor = "#ffff00";
news.style.cursor = "hand";
</script>
</body>
</html>
其中介绍下,在本例中使用的一个开源框架中有关定位的javascript脚本文件。www.young.net 提代了一个 JavaScript 库(dom-drag.js),可以帮助开发人员更快实现鼠标拖放的功能。dom-drag.js在附件中可以下载。
Css.css如下:
.root{
position:absolute;
height:150px;
width:200px;
BACKGROUND-COLOR:#eeeeee
}
.handle{
margin:2px;
padding:2px;
width:194px;
color:white;
background-color:navy;
font-family:verdana,sans-serif;
font-size:12px;
}
.text{
color:navy;
font-family:verdana,sans-serif;
font-size:12px;
}
如此就能你的拖拽功能了,大家试试吧!
例2. 褪色技术的实现
这里需要同上一个实例相同的样式,这里就不在黏贴了。
直接说主题,新建页面main2.html,代码如下:
<!DOCTYPE html PUBLIC "-//W3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="styles/style.css">
<title>Insert title here</title>
</head>
<body>
<form id="Form1" method="post">
<div id="news_root" style="LEFT:20px;TOP:20px" class="root">
<div id="news_handle" class="handle">
定制窗口
<span style="TEXT-ALIGN:right"></span>
</div>
<div id="news" class="text">
欢迎使用褪色技术
</div>
</div>
</form>
<script language="javascript">
//颜色渐变速度
var speed = 3;
//颜色渐变时需要使用的定时器对象数组
var timers;
news.style.backgroundColor = "#ffff00";
news.style.cursor = "hand";
timers = setTimeout("changeColor()",10);
function changeColor(){
var color = news.style.backgroundColor;
//当前背景颜色(rgb)的rg部分
var color_rg = color.slice(1,5);
//当前背景颜色(rgb)的b部分
//并将b部分增加一个数值,转换为10进制整数(向白色靠近)
var color_b = parseInt(color.slice(5),16) + speed;
//如果b部分不超过255
if(color_b < 255){
var b1 = Math.floor((color_b / 16)).toString(16);
var b2 = (color_b % 16).toString(16);
news.style.backgroundColor = "#" + color_rg + b1 + b2;
timers = setTimeout("changeColor()",100);
}else{
clearTimeout(timers);
}
}
</script>
</body>
</html>
完成代码后,打开页面等待5秒,你就发现颜色不断的变淡。
有建议请联系QQ:540528747,我也在学习AJAX,大家一起研究,欢迎各位朋友一起交流技术。