---
title: "〖ExtJS〗之ToolBar"
author: "seamplezeus"
date: "2012-10-21T15:10:04Z"
tags: []
categories: ["Web前端"]
slug: "extjs-toolbar"
draft: false
lastmod: "2012-10-21T15:10:04Z"
id: 1702521
url: "https://seamplezeus.iteye.com/blog/1702521"
---

面板中可以有工具栏，工具栏可以位于面板顶部或底部，Ext中工具栏是由Ext.Toolbar类表示。工具栏上可以存放按钮、文本、分隔符等内容。面板对象中内置了很多实用的工具栏，可以直接通过面板的tools配置选项往面板头部加入预定义的工具栏选项。  
比如下面的代码：

 

```
Ext.onReady(function(){
new Ext.Panel({
    renderTo:"hello",
    title:"hello",//面板标题
    width:300,
    height:300,
    html:'<h1>Hello,HelloWorld!</h1>',
    tools:[{       //生成面板右上角的工具栏
        id:"save",
      handler:function(){Ext.Msg.alert('最大化','呵呵');}    //点击工具栏调用些方法
        },
        {id:"help",
      handler:function(){Ext.Msg.alert('帮助','please help me!');}
        },
        {id:"close"}],
    tbar:[new Ext.Toolbar.TextItem('工具栏：'),//添加一文本
      {pressed:true,text:'刷新'},
      {xtype:"tbfill"},//加上这句，后面的就显示到右边去了
      {pressed:true,text:"添加"},
      {pressed:true,text:"保存"}
      ]
      });
  });
```

 

![](http://img1.51cto.com/attachment/200806/200806121213210943828.jpg)

在没有特别指定使用哪种类型的情况下，会默认自动转成按钮类型。

```
{pressed:true,text:'刷新'},
```

### 一、简单菜单

创建一个简单工具条的方法如下，注意的一点是HTML代码必须要有：&lt;div id="toolbar"&gt;&lt;/div&gt;

过程大致包括：先创建一个工具条，用工具条的render()函数把它渲染在DIV上，然后调用Toolbar的add函数，向Toolbar添加4个按钮，同时还可以添加单击处理事件。

01. Ext.onReady(function(){
02. var tb=new  Ext.Toolbar();
03. tb.render('toolbar' );
04. tb.add({
05. text:"新建N" ,
06. handler:function(){
07. Ext.Msg.alert('提示' , '新建' );
08. }
09. },{
10. text:"修改C"
11. },{
12. text:"删除"
13. },{
14. text:"显示"
15. });
16. });

效果如图1所示：

**![1](http://p.blog.csdn.net/images/p_blog_csdn_net/rocket5725/EntryImages/20090915/1633886278532968750.jpg)**

**图1 简单的工具条**

### 二、向菜单中添加分隔线

分隔线显示就是一条水平线，可以使用它将菜单中不同类型的菜单项分隔显示，Ext中向菜单中添加分隔线的方式有两种。

1、使用连字符或'separator'作为参数， 如下面的代码所示：

01. var menu1= new  Ext.menu.Menu({
02. items:[
03. {text:'菜单一' },
04. {text:'菜单二' }
05. ]
06. });
07. //menu1.add('-'); \\\\最简单的写法
08. menu1.add('separator' );
09. var tb=new  Ext.Toolbar();
10. tb.render('toolbar' );
11. tb.add({
12. text:'新建' ,
13. menu:menu1
14. });

2、用Ext.menu.Separator的实例作为参数 ，如下面的代码所示：

1. menu1.add( new  Ext.menu.Separator());

 

具体效果如图2所示：

**![2.1](http://p.blog.csdn.net/images/p_blog_csdn_net/rocket5725/EntryImages/20090915/2633886286004218750.jpg)**

**图2.1 无分隔线效果**

**![2.2](http://p.blog.csdn.net/images/p_blog_csdn_net/rocket5725/EntryImages/20090915/3633886286048437500.jpg)**

三：Ext.Toolbar.Fill

他的作用是将处于他右侧的工具条组件以右对齐的方式排列在工具条右侧

xtype:tbfill

如实例1代码所示。

 

 

四：总结：

工具条的主要作用是添加工具条组件，可参考工具条组件的xtype，还可以添加表单的输入控件，例如Ext.form.TextField形式的直接填写文字内容的输入框，还有Ext.form.DateField形式的日期选择框等其他组件。