---
title: "Flex支持滑轮滚动"
author: "yexin218"
date: "2008-06-16T18:23:33Z"
tags: ["Adobe", "Flex", "HTML", "XML"]
slug: "flex"
draft: false
lastmod: "2008-06-16T18:23:33Z"
id: 204275
url: "https://yexin218.iteye.com/blog/204275"
---

有些时候需要在Flex界面中支持鼠标的滑轮滚动功能，比如通过滑轮滚的滚动来实现对某个Field的数值增加或者递减的功能。

 实现的方法主要是利用MouseEvent.MOUSE\_WHEEL事件。在Application中的creationComplete方法中增加以下语句：

```
systemManager.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel)
```

 onMouseWheel事件处理器得到这个事件后，我们还需要监听是那个field支持而且触发了滚动事件。需要注意的是MouseEvent的currentTarget并不支持指出当前那个组件是被focus的。但是FocusManager可以帮忙：源代码如下：

```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
    creationComplete="systemManager.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel)"
    >
    <mx:TextInput id="t1"/>
    <mx:TextInput id="t2"/>  
    <mx:TextArea  id="t3"/>  
    
    <mx:Script>
        <![CDATA[
        import mx.managers.IFocusManagerComponent;
        import mx.managers.SystemManager;
        
        public function onMouseWheel (evt:MouseEvent): void {
            
            var compAtFocus: IFocusManagerComponent = focusManager.getFocus();
            
            // no wheel support unless it's a TextInput field
            if (compAtFocus is TextInput){
                var theValue:Number=Number(compAtFocus["text"]);
                theValue += evt.delta;
                compAtFocus["text"]=""+theValue;
            }  
       }         
        ]]>
    </mx:Script>
    
</mx:Application>
```

 Demo演示：【或者点击链接测试：[http://www.myflex.org/codesamples/mousewheel/MouseWheel.html](http://www.myflex.org/codesamples/mousewheel/MouseWheel.html) 】

例子中我们是检查了被focus的组件是否是TextInput,如果是执行递增或者递减的功能。如果不是比如TextArea类型的，就不具有这 个效果了。需要注意的，如果你的系统不支持滑轮滚动可能跟驱动有关，不是Flex的问题。如果你不喜欢例子中的增长或者递减数值，你可以替换掉delta 这个属性。

原创作者：[Yakov Fain](http://flexblog.faratasystems.com/?p=278%20rel%3D) 。翻译整理：[一路风尘](http://yexin218.cublog.cn/)