這次要分享一個用 JS 實作的小特效:拖動滾動條來進行評分。我個人覺得蠻有意思的。實際應用時,通常還需要搭配 ASP、PHP 或其他後端語言來取值並寫入資料庫,而這裡呈現的是純前端的實作部分。
廢話不多說,直接上程式碼,一起來見識 JS 的魔力:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>JS實現拖動<a href="https://www.jb51.net/zt/gundongtiao/" target="_blank" class="infotextkey">滾動條</a>評分的特效 (www.jb51.net)</title> <style> body{ margin:50px; ; } .scale_panel{ font-size:12px; color:#999; width:200px; position:absolute; <a href="https://www.jb51.net/article/15092.html" target="_blank" class="infotextkey">line-height</a>:18px; left:60px; top:-0px; } .scale_panel .r{ float:right; } .scale span{ width:8px; height:16px; position:absolute; left:-2px; top:-1px; cursor:pointer; } .scale{ border-left:1px #83BBD9 solid; border-right:1px red solid; width:200px; height:10px; position:relative; font-size:0px; } .scale div{ width:0px; position:absolute; width:0; left:0; height:5px; bottom:0; } li{ font-size:12px; line-height:50px; position:relative; height:50px; list-style:none; } </style> </head> <body> <ul> <li>愛情 <span id="title">0</span> <div class="scale_panel"> <span class="r">100</span>0 <div class="scale" id="bar"> <div></div> <span id="btn"></span> </div> </div> </li> <li>事業 <span id="title2">0</span> <div class="scale_panel"> <span class="r">100</span>0 <div class="scale" id="bar2"> <div></div> <span id="btn2"></span> </div> </div> </li> <li>家庭 <span id="title3">0</span> <div class="scale_panel"> <span class="r">100</span>0 <div class="scale" id="bar3"> <div></div> <span id="btn3"></span> </div> </div> </li> </ul> </body> <script> scale=function (btn,bar,title){ this.btn=document.getElementById(btn); this.bar=document.getElementById(bar); this.title=document.getElementById(title); this.step=this.bar.getElementsByTagName("DIV")[0]; this.init(); }; scale.prototype={ init:function (){ var f=this,g=document,b=window,m=Math; f.btn.onmou<a href="https://www.jb51.net/article/1141.html" target="_blank" class="infotextkey">sed</a>own=function (e){ var x=(e||b.event).clientX; var l=this.offsetLeft; var max=f.bar.offsetWidth-this.offsetWidth; g.onmousemove=function (e){ var thisX=(e||b.event).clientX; var to=m.min(max,m.max(-2,l+(thisX-x))); f.btn.style.left=to+'px'; f.ondrag(m.round(m.max(0,to/max)*100),to); b.getSelection ? b.getSelection().removeAllRanges() : g.selection.empty(); }; g.onmouseup=new Function('this.onmousemove=null'); }; }, ondrag:function (pos,x){ this.step.style.width=Math.max(0,x)+'px'; this.title.innerHTML=pos+'%'; } } new scale('btn','bar','title'); new scale('btn2','bar2','title2'); new scale('btn3','bar3','title3'); </script> <br /> </html> 這段程式把「拖動」封裝成一個 scale 建構函式,透過原型方法 init 綁定滑鼠事件,並在 ondrag 中即時更新進度條寬度與百分比文字。由於每組評分項(愛情、事業、家庭)都各自 new 一個實例,因此彼此互不干擾,能同時獨立操作。這種把互動邏輯抽象成可複用類別的寫法,之後要擴充更多評分維度時會輕鬆許多。