#num_up,#num_down{position:absolute; right:6px; top:18px; font-size:20px;}
#dig_up p{height:24px; line-height:24px; color:#360}
#dig_down p{height:24px; line-height:24px; color:#f30}
.bar{width:100px; height:12px; line-height:12px; border:1px solid #f0f0f0;
position:relative; text-align:center}
.bar span{display:block; height:12px; }
.bar i{position:absolute; top:0; left:104px;}
#bar_up span{background:#360}
#bar_down span{background:#f60}
#msg{position:absolute; right:20px; top:40px; font-size:18px; color:#f00}
jQuery
本示例还依赖于jQuery,因此一定不能忘了在页面中先载入jquery库文件。
首先,jQuery要处理的是鼠标分别滑向两个投票按钮时变换的背景图片,通过addClass()和removeClass()来实现。
$(function(){
//鼠标滑向和离开投票按钮时,变换背景样式
$("#dig_up").hover(function(){
$(this).addClass("digup_on");
},function(){
$(this).removeClass("digup_on");
});
$("#dig_down").hover(function(){
$(this).addClass("digdown_on");
},function(){
$(this).removeClass("digdown_on");
});
//初始化数据
getdata("do.php",1);
//单击“顶”时
$("#dig_up").click(function(){
getdata("do.php?action=like",1);
});
//单击“踩”时
$("#dig_down").click(function(){
getdata("do.php?action=unlike",1);
});
});
然后,我们初始化数据,就是页面加载后,要显示初始的已经投票的结果,包括各投票数和所占百分比。我们将获取数据的操作写在一个自定义函数getdata()中,通过传递不同的请求地址和id参数来完成数据的载入。函数getdata()中,向URL发送一个ajax请求,根据后台处理的返回结果,如果投票成功则更改页面中相应的元素内容,包括投票数和所占百分比。
function getdata(url,sid){
$.getJSON(url,{id:sid},function(data){
if(data.success==1){//投票成功
$("#num_up").html(data.like);
//通过控制宽度来显示百分比进度条效果
$("#bar_up span").css("width",data.like_percent);
$("#bar_up i").html(data.like_percent);
$("#num_down").html(data.unlike);
$("#bar_down span").css("width",data.unlike_percent);
$("#bar_down i").html(data.unlike_percent);
}else{//投票失败
$("#msg").html(data.msg).show().css({'opacity':1,'top':'40px'})
.animate({top:'-50px',opacity:0}, "slow");
}
});
}
PHP
数据的获取都是通过do.php来完成,do.php根据前端页面传递的参数,连接数据库,根据条件判断分别进入“顶”、“踩”和初始数据处理模块,以下是do.php模块代码结构:










