本篇文章主要介绍PHP+jQuery+MySql实现红蓝投票实例,感兴趣的朋友参考下,希望对大家有所帮助。
先给大家展示效果图:
HTML
我们需要在页面中展示红蓝双方的观点,以及对应的投票数和比例,以及用于投票交互的手型图片,本例以#red和#blue分别表示红蓝双方。.redhand和.bluehand用来做手型投票按钮,.redbar和.bluebar展示红蓝双方比例调,#red_num和#blue_num展示双方投票数。
<p class="vote"> <p class="votetitle">您对<a href="http://www.gaodaima.com">搞代码</a>提供的文章的看法?</p> <p class="votetxt">非常实用<span>完全看不懂</span></p> <p class="red" id="red"> <p class="redhand"></p> <p class="redbar" id="red_bar"> <span></span> <p id="red_num"></p> </p> </p> <p class="blue" id="blue"> <p class="bluehand"></p> <p class="bluebar" id="blue_bar"> <span></span> <p id="blue_num"></p> </p> </p> &<i>*本5文来源gaodai$ma#com搞$$代**码)网@</i><img>搞代码gaodaima</img>lt;/p>
CSS
使用CSS将页面美化,加载背景图片,确定相对位置等等,你可以直接复制以下代码,在自己的项目中稍作修改即可。
.vote{width:288px; height:220px; margin:60px auto 20px auto;position:relative} .votetitle{width:100%;height:62px; background:url(icon.png) no-repeat 0 30px; font-size:15px} .red{position:absolute; left:0; top:90px; height:80px;} .blue{position:absolute; right:0; top:90px; height:80px;} .votetxt{line-height:24px} .votetxt span{float:right} .redhand{position:absolute; left:0;width:36px; height:36px; background:url(icon.png) no-repeat -1px -38px;cursor:pointer} .bluehand{position:absolute; right:0;width:36px; height:36px; background:url(icon.png) no-repeat -41px -38px;cursor:pointer} .grayhand{width:34px; height:34px; background:url(icon.png) no-repeat -83px -38px;cursor:pointer} .redbar{position:absolute; left:42px; margin-top:8px;} .bluebar{position:absolute; right:42px; margin-top:8px; } .redbar span{display:block; height:6px; background:red; width:100%;border-radius:4px;} .bluebar span{display:block; height:6px; background:#09f; width:100%;border-radius:4px; position:absolute; right:0} .redbar p{line-height:20px; color:red;} .bluebar p{line-height:20px; color:#09f; text-align:right; margin-top:6px}
jQuery
当点击手型按钮时,利用jQuery的$.getJSON()向后台php发送Ajax请求,如果请求成功,将会得到后台返回的json数据,jQuery再将json数据进行处理。以下函数:getdata(url,sid),传递了两个参数,url是请求的后台php地址,sid表示当前投票主题ID,我们在该函数中,返回的json数据有红蓝双方的投票数,以及双方比例,根据比例计算比例条的宽度,异步交互展示投票效果。
function getdata(url,sid){ $.getJSON(url,{id:sid},function(data){ if(data.success==1){ var w = 208; //定义比例条的总宽度 //红方投票数 $("#red_num").html(data.red); $("#red").css("width",data.red_percent*100+"%"); var red_bar_w = w*data.red_percent-10; //红方比例条宽度 $("#red_bar").css("width",red_bar_w); //蓝方投票数 $("#blue_num").html(data.blue); $("#blue").css("width",data.blue_percent*100+"%"); var blue_bar_w = w*data.blue_percent; //蓝方比例条宽度 $("#blue_bar").css("width",blue_bar_w); }else{ alert(data.msg); } }); }