本實例演示了實現一個滾動條基本功能的制作方法,沒有添加改變皮膚,修改滾動條視框大小等功能,有興趣的朋友可根據自己要求自行添加。使用時只需要通過以下一行代碼創建滾動條組件:
var myScrollbar:Scrollbar=new Scrollbar(mc); addChild(myScrollbar);
其中mc為需要添加滾動條功能的元件,如影片剪輯,文本等。
一、制作元件
滾動條由滑塊slider,向上向下滾動的按鈕,滾動條背景,遮擋內容的遮罩及存儲內容的contMc元素組成。當拖動滑塊slider或單擊上下按鈕時,contMc會上下滾動。制作元件並命名如下:
二、為滾動條的庫元件添加鏈接(如下圖所示)
三、鏈接的類代碼
全局變量說明:step為滾動步數,top為slider滑塊在最頂端的位置,buttom為滑塊在最低端的位置。
1 package { 2 3 import flash.display.MovieClip; 4 import flash.display.DisplayObject; 5 import flash.events.Event; 6 import flash.events.MouseEvent; 7 8 public class Scrollbar extends MovieClip { 9 10 private var step:int=5; 11 private var top:Number; 12 private var buttom:Number; 13 14 public function Scrollbar(mc:DisplayObject) { 15 this.contMc.addChild(mc); 16 mc.x=0; 17 mc.y=0; 18 this.addEventListener(Event.ADDED_TO_STAGE,init); 19 } 20 21 private function init(e:Event):void { 22 top=this.slider.height/2; 23 buttom=this.back.height-this.slider.height/2; 24 this.downBtn.addEventListener(MouseEvent.CLICK,downHandler); 25 this.upBtn.addEventListener(MouseEvent.CLICK,upHandler); 26 this.slider.addEventListener(MouseEvent.MOUSE_DOWN,sliderDrag); 27 } 28 29 private function downHandler(e:MouseEvent):void { 30 if(this.slider.y<buttom){ 31 this.slider.y+=step; 32 } 33 if(this.slider.y>buttom){ 34 this.slider.y=buttom; 35 } 36 moveContMc(); 37 } 38 39 private function upHandler(e:MouseEvent):void { 40 if(this.slider.y>top){ 41 this.slider.y-=step; 42 } 43 if(this.slider.y<top){ 44 this.slider.y=top; 45 } 46 moveContMc() 47 } 48 49 private function sliderDrag(e:MouseEvent):void { 50 this.stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler); 51 this.addEventListener(Event.ENTER_FRAME,enterFrameHandler); 52 53 } 54 55 private function mouseUpHandler(e:MouseEvent):void { 56 this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler); 57 } 58 59 private function enterFrameHandler(e:Event):void { 60 this.slider.y=Math.min(buttom,Math.max(top,this.mouseY)); 61 moveContMc(); 62 } 63 64 private function moveContMc():void { 65 this.contMc.y=-(this.contMc.height-this.back.height)*(this.slider.y-top)/buttom; 66 } 67 68 } 69 }
四、moveContMc函數解析:
如下圖左示意,當slider滑塊由最頂端(top位置)向下移動距離b時,contMc會向上移動距離a。如下圖右,當滑塊移動到最低端(buttom位置)時,contMc會移動到最頂端,距離為m(值為contMc的高度-遮罩層的高度),由a/b=m/n,可算出a值為m*b/n,即:
this.contMc.y=-(this.contMc.height-this.back.height)*(this.slider.y-top)/buttom;