Script.aculo.us 简明教程
script.aculo.us - Overview
What is script.aculo.us?
script.aculo.us 是一个 JavaScript 库,建立在 Prototype JavaScript 框架之上,增强了 GUI,并为 Web 用户提供了 Web 2.0 体验。
script.aculo.us is a JavaScript library built on top of the Prototype JavaScript Framework, enhancing the GUI and giving Web 2.0 experience to the web users.
script.aculo.us 由托马斯·福克斯开发,并于 2005 年 6 月首次向公众发布。
script.aculo.us was developed by Thomas Fuchs and it was first released to the public in June 2005.
script.aculo.us 通过文档对象模型 (DOM) 提供动态视觉效果和用户界面元素。
script.aculo.us provides dynamic visual effects and user interface elements via the Document Object Model (DOM).
Prototype JavaScript 框架是由塞姆·斯蒂芬森创建的 JavaScript 框架,它提供了 Ajax 框架和其他实用工具。
The Prototype JavaScript Framework is a JavaScript framework created by Sam Stephenson that provides an Ajax framework and other utilities.
How to Install script.aculo.us?
安装 script.aculo.us 库非常简单。它可以通过三个简单步骤设置 −
It is quite simple to install the script.aculo.us library. It can be set up in three simple steps −
-
Go to the download page to download the latest version in a convenient package.
-
Unpack the downloaded package and you will find the following folders − lib − contains prototype.js file. src − contains the following 8 files − builder.jscontrols.jsdragdrop.jseffects.jsscriptaculous.jsslider.jssound.jsunittest.js*test* − contains files for testing purpose. CHANGELOG − File that contains the history of all the changes. MIT-LICENSE − File describing the licensing terms. README − File describing the installation package including the installation instructions.
-
Now put the following files in a directory of your website, e.g. /javascript. builder.jscontrols.jsdragdrop.jseffects.jsscriptaculous.jsslider.jsprototype.js
NOTE - sound.js 和 unittest.js 文件是可选的
NOTE − The sound.js and unittest.js files are optional
How to Use script.aculo.us Library?
现在你可以按照以下方式包含 script.aculo.us 脚本:
Now you can include script.aculo.us script as follows −
<html>
<head>
<title>script.aculo.us examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script >
</head>
<body>
........
</body>
</html>
默认情况下,scriptaculous.js 加载效果、拖放、滑块和所有其他 script.aculo.us 特征所需的全部其他 JavaScript 文件。
By default, scriptaculous.js loads all of the other JavaScript files necessary for effects, drag-and-drop, sliders, and all the other script.aculo.us features.
如果你不需要全部特征,你可以通过按逗号分隔的方式指定额外的脚本,限制被加载的脚本,例如:
If you don’t need all the features, you can limit the additional scripts that get loaded by specifying them in a comma-separated list, e.g. −
<html>
<head>
<title>script.aculo.us examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
</head>
<body>
........
</body>
</html>
可以指定以下脚本:
The scripts that can be specified are −
-
effects
-
dragdrop
-
builder
-
controls
-
slider
NOTE - 有些脚本需要加载其他脚本才能正常运行。
NOTE − Some of the scripts require that others be loaded in order to function properly.
How to Call a script.aculo.us Library Function?
要调用 script.aculo.us 库函数,请使用如下所示的 HTML 脚本标签 -
To call a script.aculo.us library function, use HTML script tags as shown below −
<html>
<head>
<title>script.aculo.us examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
<script type = "text/javascript" language = "javascript">
// <![CDATA[
function action(element){
new Effect.Highlight(element,
{ startcolor: "#ff0000", endcolor: "#0000ff", restorecolor: "#00ff00", duration: 8 });
}
// ]]>
</script>
</head>
<body>
<div id = "id" onclick = "action(this);">
Click on this and see how it change its color.
</div>
</body>
</html>
在这里,我们使用 Effect 模块,并将 Highlight 效果应用到一个元素上。
Here we are using the Effect module and we are applying Highlight effect on an element.
这将生成以下结果:
This will produce following result −
另一种简单的方法是在事件处理程序中调用任何模块的函数,如下所示-
Another easy way to call any module’s function is inside event handlers as follows −
<html>
<head>
<title>script.aculo.us examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
</head>
<body>
<div onclick = "new Effect.BlindUp(this, {duration: 5})">
Click here if you want this to go slooooow.
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
script.aculo.us - Modules
script.aculo.us 被划分为模块,每个模块都有其自己的 JavaScript 文件。此处对这些模块进行了说明 −
script.aculo.us is divided into modules, each with its own JavaScript file. These modules are explained here −
Effects
effects 模块包含二十五种以上的视觉效果和七种过渡模式。
The effects module comes with more than twenty-five visual effects and seven transition modes.
Drag and Drop
你将使用 drag and drop 模块使任何元素可拖动,将其变成一个拖放区域,甚至可以使整个系列元素可排序,以便你可以通过拖放重新排列它们。
You will use the drag and drop module to make any element draggable, turn it into a drop zone, or even make an entire series of elements sortable so that you can rearrange them by dragging and dropping.
Sliders
滑块是一种带有轨道或轨迹的小型控件,你可以在其上滑动一个手柄。它会转换为数值。你可以使用 script.aculo.us 创建出各种可控的滑块。
A slider is a sort of small rail or track, along which you can slide a handle. It translates into a numerical value. With script.aculo.us, you can create such sliders with a lot of control.
Autocompletion
Autocompleter 控件允许使用 Google Suggest 风格、本地和由服务器支持的自动完成文本输入字段。
Autocompleter controls allow Google-Suggest style, local and server-powered autocompleting text input fields.
In-place Editing
只要单击,即可让任何文本或集合中的项目就地可编辑。
You can make any text or collection of items editable in-place by simply clicking it.
script.aculo.us - Visual Effects
script.aculo.us 效果分为两组 −
The script.aculo.us effects are divided into two groups −
Core Effects
以下六个核心效果是 script.aculo.us Visual Effects JavaScript 库的基础。
The following six core effects are the foundation of the script.aculo.us Visual Effects JavaScript library.
所有核心效果均支持各种常见参数和特有效果参数,这些效果名称区分大小写。
All the core effects support various common parameters as well as effect-specific parameters and these effect names are case-sensitive.
本教程详细讨论了所有特有 Common Parameters 和效果。
All the effect-specific Common Parameters have been discussed in this tutorial along with the effects.
Combination Effects
所有组合效果均基于五个核心效果,被视为允许编写自己效果的示例。
All the combination effects are based on the five Core Effects, and are thought of as examples to allow you to write your own effects.
通常,这些效果依赖于其他效果的并行、同步执行。这种执行非常方便,因此创建 eigene 组合效果很容易。以下是组合效果的列表 −
Usually these effects rely on the parallel, synchronized execution of other effects. Such an execution is readily available, hence creating your own combined effects is very easy. Here is a list of Combination Effects −
此外,还有 Effect.toggle 实用方法,可用于想要临时显示元素,并带出现/淡入淡出、滑动或盲目的效果。
Additionally, there’s the Effect.toggle utility method for elements you want to show temporarily with an Appear/Fade, Slide or Blind animation.
Library Files Required for Effects
为了使用 script.aculo.us 的效果功能,你需要加载 effects 模块。因此,面向 script.aculo.us 的最小加载看上去如下:
To use the effect capabilities of script.aculo.us, you will need to load the effects module. So, your minimum loading for script.aculo.us will look like this:
<html>
<head>
<title>script.aculo.us effects</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/"effects.j"></script>
</head>
<body>
...
</body>
</html>
Call Effect Functions
启动核心效果的正确方法通常是使用 new 运算符。根据偏好,你可以使用两种语法之一 −
The proper way to start a core effect is usually with the new operator. Depending on your preferences, you can use one of two syntaxes −
Syntax
new Effect.EffectName(element [, requiredArgs ] [ , options ] )
OR
element.visualEffect('EffectName' [, requiredArgs ] [,options])
这两条语法在技术上是等价的。在两者之间的选择主要取决于你个人的代码美学感。
These two syntaxes are technically equivalent. Choosing between the two is mostly about your personal sense of code aesthetics.
Example
以下是两个等价的调用,让你看到语法之间的关系,它们都是可互换的 −
Here are two equivalent calls, so you can see how the syntaxes are related, which are very much interchangeable −
new Effect.Scale('title', 200, { scaleY: false, scaleContent: false });
OR
$('title' ).visualEffect('Scale', 200, { scaleY:false, scaleContent:false });
script.aculo.us - Drag & Drop
Web 2.0 界面的最受欢迎功能就是拖放。幸运的是,script.aculo.us 附带了固有功能以支持拖放。
The most popular feature of Web 2.0 interface is the drag and drop facility. Fortunately script.aculo.us comes with an inherent capability to support drag and drop.
要使用 script.aculo.us 的拖动功能,您需要加载 dragdrop 模块,该模块同时需要 effects 模块。因此,您对 script.aculo.us 进行的最低加载看上去像下面这样:
To use the dragging capabilities of script.aculo.us, you’ll need to load the dragdrop module, which also requires the effects module. So your minimum loading for script.aculo.us will look like this:
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
Dragging Things Around
使用 script.aculo.us 制作可拖动的项目非常简单。它需要创建 Draggable 类的实例,并识别要制作成可拖动的元素。
It is very simple to make an item draggable using script.aculo.us. It requires creating an instance of the Draggable class, and identifying the element to be made draggable.
Draggable Syntax
new Draggable( element, options );
构造函数的第一个参数使用元素的 id 或对该元素的引用来标识要制作成可拖动的元素。第二个参数指定有关可拖动元素行为方式的可选信息。
The first parameter to the constructor identifies the element to be made draggable either as the id of the element, or a reference to the element. The second parameter specifies optional information on how the draggable element is to behave.
Draggable Options
创建可拖动对象时,您可以使用以下一个或多个选项。
You can use one or more of the following options while creating your draggable object.
Option |
Description |
Examples |
revert |
If set to true, the element returns to its original position when the drag ends. Also specifies whether the reverteffect callback will be invoked when the drag operation stops. Defaults to false. |
|
snap |
Used to cause a draggable to snap to a grid or to constrain its movement. If false (default), no snapping or constraining occurs. If it is assigned an integer x, the draggable will snap to a grid of x pixels. If an array [x, y], the horizontal dragging will snap to a grid of x pixels and the vertical will snap to y pixels. It can also be a function conforming to Function( x , y , draggable ) that returns an array [x, y]. |
|
zindex |
Specifies the CSS z-index to be applied to the element during a drag operation. By default, the element’s z-index is set to 1000 while dragging. |
|
ghosting |
Boolean determining whether the draggable should be cloned for dragging, leaving the original in place until the clone is dropped. Defaults to false. |
|
constraint |
A string used to limit the draggable directions, either horizontal or vertical. Defaults to null which means free movement. |
|
handle |
Specifies an element to be used as the handle to start the drag operation. By default, an element is its own handle. |
|
starteffect |
An effect called on element when dragging starts. By default, it changes the element’s opacity to 0.2 in 0.2 seconds. |
|
reverteffect |
An effect called on element when the drag is reverted. Defaults to a smooth slide to element’s original position.Called only if revert is true. |
|
endeffect |
An effect called on element when dragging ends. By default, it changes the element’s opacity to 1.0 in 0.2 seconds. |
Callback Options
此外,你可以在 options 参数中使用以下任何回调函数 −
Additionally, you can use any of the following callback functions in the options parameter −
Function |
Description |
Examples |
onStart |
Called when a drag is initiated. |
|
onDrag |
Called repeatedly when a mouse moves, if mouse position changes from previous call. |
|
change |
Called just as onDrag (which is the preferred callback). |
|
onEnd |
Called when a drag is ended. |
除了“change”回调外,每个这些回调都接受两个参数:可拖动对象和鼠标事件对象。
Except for the "change" callback, each of these callbacks accepts two parameters: the Draggable object, and the mouse event object.
Draggable Example
在此,我们定义了 5 个可拖动元素:三个 <div> 元素、一个 <img> 元素和一个 <span> 元素。三个不同的 <div> 元素的目的是演示以下行为:无论元素最初以何种定位规则(默认值)、相对定位还是绝对定位开始,都不会影响拖拽行为。
Here, we define 5 elements that are made draggable: three <div> elements, an <img> element, and a <span> element. The purpose of the three different <div> elements is to demonstrate that regardless of whether an element starts off with a positioning rule of static (the default), relative, or absolute, the drag behavior is unaffected.
<html>
<head>
<title>Draggables Elements</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
// Take all the elements whatever you want to make Draggable.
var elements = ['normaldiv', 'relativediv', 'absolutediv', 'image', 'span'];
// Make all the items drag able by creating Draggable objects
window.onload = function() {
elements.each(function(item) { new Draggable(item, {});});
}
</script>
</head>
<body>
<div id = "normaldiv">
This is a normal div and this is dragable.
</div>
<div id = "relativediv" style="position: relative;">
This is a relative div and this is dragable.
</div>
<div id = "absolutediv" style="position: absolute;">
This is an absolute div and this dragable.
</div>
<br />
<img id = "image" src = "/images/scriptaculous.gif"/>
<p>Let part <span id = "span" style = "color: blue;">
This is middle part</span> Yes, only middle part is dragable.</p>
</body>
</html>
这将生成以下结果:
This will produce following result −
Dropping Dragged Things
通过对 Droppables 名称空间中 add() 方法的调用,可以将某个元素转换为一个拖放目标。
An element is converted into a drop target via a call to the add() method within a namespace called Droppables.
Droppables 名称空间有两种重要的方法:add() 用于创建拖放目标,remove() 用于移除拖放目标。
The Droppables namespace has two important methods: add() to create a drop target, and remove() to remove a drop target.
Syntax
以下是创建拖放目标的 add() 方法的语法。add() 方法创建一个拖放目标,作为其第一个参数传递的元素,使用作为第二个参数传递的 hash 中的选项。
Here is the syntax of the add() method to create a drop target. The add() method creates a drop target out of the element passed as its first parameter, using the options in the hash passed as the second.
Droppables.add( element, options );
remove() 的语法甚至更为简单。remove() 方法从传递的元素中移除拖放目标行为。
The syntax for remove() is even more simpler. The remove() method removes the drop target behavior from the passed element.
Droppables.remove(element);
Options
创建可拖动对象时,您可以使用以下一个或多个选项。
You can use one or more of the following options while creating your draggable object.
Option |
Description |
Examples |
Hoverclass |
The name of a CSS class that will be added to the element while the droppable is active (has an acceptable draggable hovering over it). Defaults to null. |
|
Accept |
A string or an array of strings describing CSS classes. The droppable will only accept draggables that have one or more of these CSS classes. |
|
Containment |
Specifies an element, or array of elements, that must be a parent of a draggable item in order for it to be accepted by the drop target. By default, no containment constraints are applied. |
|
Overlap |
If set to 'horizontal' or 'vertical', the droppable will only react to a Draggable if its overlapping by more than 50% in the given direction. Used by Sortables, discussed in the next chapter. |
|
greedy |
If true (default), it stops hovering other droppables, under the draggable won’t be searched. |
Callback Options
此外,你可以在 options 参数中使用以下任何回调函数 −
Additionally, you can use any of the following callback functions in the options parameter −
Function |
Description |
Examples |
onHover |
Specifies a callback function that is activated when a suitable draggable item hovers over the drop target. Used by Sortables, discussed in the next chapter. |
|
onDrop |
Specifies a callback function that is called when a suitable draggable element is dropped onto the drop target. |
Example
在此,此示例的第一部分与我们之前的示例类似,只不过我们使用了 Prototype 的方便 $A() 函数,将具有 id 为 draggables 的元素中所有 <img> 元素的节点列表转换为一个数组。
Here, the first part of this example is similar to our previous example, except that we have used Prototype’s handy $A() function to convert a node list of all the <img> elements in the element with the id of draggables to an array.
<html>
<head>
<title>Drag and Drop Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
window.onload = function() {
// Make all the images draggables from draggables division.
$A($('draggables').getElementsByTagName('img')).each(function(item) {
new Draggable(item, {revert: true, ghosting: true});
});
Droppables.add('droparea', {hoverclass: 'hoverActive', onDrop: moveItem});
// Set drop area by default non cleared.
$('droparea').cleared = false;
}
// The target drop area contains a snippet of instructional
// text that we want to remove when the first item
// is dropped into it.
function moveItem( draggable,droparea){
if (!droparea.cleared) {
droparea.innerHTML = '';
droparea.cleared = true;
}
draggable.parentNode.removeChild(draggable);
droparea.appendChild(draggable);
}
</script>
<style type = "text/css">
#draggables {
width: 172px;
border: 3px ridge blue;
float: left;
padding: 9px;
}
#droparea {
float: left;
margin-left: 16px;
width: 172px;
border: 3px ridge maroon;
text-align: center;
font-size: 24px;
padding: 9px;
float: left;
}
.hoverActive {
background-color: #ffffcc;
}
#draggables img, #droparea img {
margin: 4px;
border:1px solid red;
}
</style>
</head>
<body>
<div id = "draggables">
<img src = "/images/html.gif"/>
<img src = "/images/css.gif"/>
<img src = "/images/xhtml.gif"/>
<img src = "/images/wml_logo.gif"/>
<img src = "/images/javascript.gif"/>
</div>
<div id = "droparea">
Drag and Drop Your Images in this area
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
script.aculo.us - Sorting Elements
很多时候,你需要为用户提供通过拖拽来重新排列元素的功能(比如列表中的项目)。
Many times, you need to provide the user with the ability to reorder elements (such as items in a list) by dragging them.
如果没有拖放,重新排列会是一场噩梦,但是 script.aculo.us 通过 Sortable 类提供了开箱即用的扩展重新排列支持。成为 Sortable 的元素传递给 Sortable 命名空间中的 create() 方法。
Without drag and drop, reordering can be a nightmare, but script.aculo.us provides extended reordering support out of the box through the Sortable class. The element to become Sortable is passed to the create() method in the Sortable namespace.
Sortable 由容器元素中的项目元素组成。当你创建一个新的 Sortable 时,它会负责创建相应的 Draggables 和 Droppables。
A Sortable consists of item elements in a container element. When you create a new Sortable, it takes care of the creation of the corresponding Draggables and Droppables.
若要使用 script.aculo.us 的 Sortable 功能,你需要加载 dragdrop 模块,它还需要 effects 模块。所以,你的 script.aculo.us 最小加载将如下所示 −
To use script.aculo.us’s Sortable capabilities, you’ll need to load the dragdrop module, which also requires the effects module. So your minimum loading for script.aculo.us will look like this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,dragdrop"></script>
Sortable Syntax
以下是创建一个可排序项目的 create() 方法的语法。create() 方法接受容器元素的 id,并根据传递的选项对它们进行排序。
Here is the syntax of the create() method to create a sortable item. The create() method takes the id of a container element and sorts them out based on the passed options.
Sortable.create('id_of_container',[options]);
针对 Sortable.create 创建的 Sortable,使用 Sortable.destroy 来完全移除所有事件处理程序和引用。
Use Sortable.destroy to completely remove all the event handlers and references to a Sortable created by Sortable.create.
NOTE − 对 Sortable.create 的调用,如果引用元素已经是 Sortable,则隐式地调用 Sortable.destroy。以下是调用 destroy 函数的简单语法。
NOTE − A call to Sortable.create, implicitly calls on Sortable.destroy if the referenced element was already a Sortable. Here is the simple syntax to call the destroy function.
Sortable.destroy( element );
Sortable Options
创建 Sortable 对象时,你可以使用以下一个或多个选项。
You can use one or more of the following options while creating your Sortable object.
Sr.No |
Option & Description |
1 |
tag Specifies the type of the elements within the sortable container that are to be sortable via drag and drop. Defaults to 'li'. |
2 |
only Specifies a CSS class name, or array of class names, that a draggable item must posses in order to be accepted by the drop target. This is similar to the accept option of Draggable. By default, no class name constraints are applied. |
3 |
overlap One of false, horizontal or vertical. Controls the point at which a reordering is triggered. Defaults to vertical. |
4 |
constraint One of false, horizontal or vertical. Constrains the movement of dragged sortable elements. Defaults to vertical. |
5 |
containment Enables dragging and dropping between Sortables. Takes an array of elements or element-ids. Important note: To ensure that two way dragging between containers is possible, place all Sortable.create calls after the container elements. |
6 |
handle Same as the Draggable option of the same name, specifying an element to be used to initiate drag operations. By default, each element is its own handle. |
7 |
hoverclass Specifies a CSS class name to be applied to non-dragged sortable elements as a dragged element passes over them. By default, no CSS class name is applied. |
8 |
ghosting Similar to the Draggable option of the same name, If true, this option causes the original element of a drag operation to stay in place while a semi-transparent copy of the element is moved along with the mouse pointer. Defaults to false. This option does not work with IE. |
9 |
dropOnEmpty If true, it allows sortable elements to be dropped onto an empty list. Defaults to false. |
10 |
scroll If the sortable container possesses a scrollbar due to the setting of the CSS overflow attribute, this option enables auto-scrolling of the list beyond the visible elements. Defaults to false. |
12 |
scrollSensitivity When scrolling is enabled, it adjusts the point at which scrolling is triggered. Defaults to 20. |
13 |
scrollSpeed When scrolling is enabled, it adjusts the scroll speed. Defaults to 15. |
14 |
tree If true, it enables sorting with sub-elements within the sortable element. Defaults to false. |
15 |
treeTag If the tree option is enabled, it specifies the container element type of the sub-element whose children takes part in the sortable behavior. Defaults to 'ul'. |
可以在选项参数中提供以下回调 −
You can provide the following callbacks in the options parameter −
Sr.No |
Option & Description |
1 |
onChange A function that will be called upon whenever the sort order changes while dragging. When dragging from one Sortable to another, the callback is called once on each Sortable. Gets the affected element as its parameter. |
2 |
onUpdate A function that will be called upon the termination of a drag operation that results in a change in element order. |
Sorting Examples
此演示已在 IE 6.0 中经过验证正常工作。它还适用于 Firefox 的最新版本。
This demo has been verified to work in IE 6.0. It also works in the latest version of Firefox.
<html>
<head>
<title>Sorting Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
window.onload = function() {
Sortable.create('namelist',{tag:'li'});
}
</script>
<style type = "text/css">
li { cursor: move; }
</style>
</head>
<body>
<p>Drag and drop list items to sort them out</p>
<ul id = "namelist">
<li>Physics</li>
<li>Chemistry</li>
<li>Maths</li>
<li>Botany</li>
<li>Sociology</li>
<li>English</li>
<li>Hindi</li>
<li>Sanskrit</li>
</ul>
</body>
</html>
使用我们的在线编译器,更好地理解上面表格中讨论的各种选项的代码。
Use our online compiler for a better understanding of the code with different options discussed in the above table.
这将生成以下结果:
This will produce following result −
请注意 tag:'li' 的用法。同样地,可以对 <div> 中提供的以下图像列表进行排序 −
Note the usage of tag:'li'. Similarly, you can sort the following list of images available in <div> −
<html>
<head>
<title>Sorting Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
window.onload = function() {
Sortable.create('imagelist',{tag:'div'});
}
</script>
<style type = "text/css">
div { cursor: move; }
img { border: 1px solid red; margin:5px; }
</style>
</head>
<body>
<p>Drag and drop list images to re-arrange them</p>
<div id = "imagelist">
<div><img src = "/images/wml_logo.gif" alt="WML Logo" /></div>
<div><img src = "/images/javascript.gif" alt="JS" /></div>
<div><img src = "/images/html.gif" alt="HTML" /></div>
<div><img src = "/images/css.gif" alt="CSS" /></div>
</div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Serializing the Sortable Elements
Sortable 对象还提供了一个函数 Sortable.serialize(),用于以适用于 HTTP GET 或 POST 请求的格式对 Sortable 进行序列化。这可用于通过 Ajax 调用提交 Sortable 的顺序。
The Sortable object also provides a function Sortable.serialize() to serialize the Sortable in a format suitable for HTTP GET or POST requests. This can be used to submit the order of the Sortable via an Ajax call.
Options
创建 Sortable 对象时,你可以使用以下一个或多个选项。
You can use one or more of the following options while creating your Sortable object.
Sr.No |
Option & Description |
1 |
tag Sets the kind of tag that will be serialized. This will be similar to what is used in Sortable.create. |
2 |
name Sets the name of the key that will be used to create the key/value pairs for serializing in HTTP GET/POST format. So if the name were to be xyz, the query string would look like − xyz[]=value1 & xyz[]=value2 & xyz[]=value3 Where the values are derived from the child elements in the order that they appear within the container. |
Serialize Examples
在此示例中,序列化的输出将只提供列表项 ID 中下划线后的数字。
In this example, the output of the serialization will only give the numbers after the underscore in the list item IDs.
要尝试,让列表保持其原始顺序,按按钮查看列表的序列化。现在,重新排列一些元素,然后再次单击按钮。
To try, leave the lists in their original order, press the button to see the serialization of the lists. Now, re-order some elements and click the button again.
<html>
<head>
<title>Sorting Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
window.onload = function() {
Sortable.create('namelist',{tag:'li'});
}
function serialize(container, name){
$('display').innerHTML = 'Serialization of ' +
$(container).id +
' is: <br/><pre>' +
Sortable.serialize( container,{ name:name} ) +
'</pre>';
}
</script>
<style type = "text/css">
li { cursor: move; }
</style>
</head>
<body>
<p>Drag and drop list items to sort them out properly</p>
<ul id = "namelist">
<li id = "list1_1">Physics</li>
<li id = "list1_2">Chemistry</li>
<li id = "list1_3">Maths</li>
<li id = "list1_4">Botany</li>
<li id = "list1_5">Sociology</li>
<li id = "list1_6">English</li>
</ul>
<p>Click following button to see serialized list which can be
passed to backend script, like PHP, AJAX or CGI</p>
<button type = "button" value = "Click Me"
onclick = "serialize('namelist', 'list')"> Serialize
</button>
<div id = "display" style = "clear:both;padding-top:32px"></div>
</body>
</html>
这将生成以下结果:
This will produce following result −
Moving Items between Sortables
以下示例显示如何将项目从一个列表移动到另一个列表。
The following example shows how to move items from one list to another list.
<html>
<head>
<title>Sorting Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
window.onload = function() {
Sortable.create('List1', {containment: ['List1','List2'], dropOnEmpty: true});
Sortable.create('List2', {containment: ['List1','List2'], dropOnEmpty: true});
}
</script>
<style type = "text/css">
li { cursor: move; }
ul {
width: 88px;
border: 1px solid blue;
padding: 3px 3px 3px 20px;
}
</style>
</head>
<body>
<p>Drag and drop list items from one list to another list</p>
<div style = "float:left">
<ul id = "List1">
<li>Physics</li>
<li>Chemistry</li>
<li>Botany</li>
</ul>
</div>
<div style = "float:left;margin-left:32px">
<ul id = "List2">
<li>Arts</li>
<li>Politics</li>
<li>Economics</li>
<li>History</li>
<li>Sociology</li>
</ul>
</div>
</body>
</html>
请注意,每个容器的 containment 选项将两个容器都列为 containment 元素。通过执行此操作,已启用在它们各自父级的上下文中对子元素进行排序;它还允许在两个容器之间移动这些子元素。
Note that the containment option for each container lists both the containers as containment elements. By doing so, we have enabled the child elements to be sorted within the context of their parent; It also enables them to be moved between the two containers.
针对两个列表都将 dropOnEmpty 设置为 true。若要查看此选项对该列表产生的影响,请将一个列表中的所有元素移动到另一个列表中,以便使一个列表为空。你将发现它允许在空列表上放置元素。
We set dropOnEmpty to true for both the lists. To see the effect this option has on that list, move all the elements from one list into other so that one list is empty. You will find that it is allowing to drop element on empty list.
这将生成以下结果:
This will produce following result −
Binding to Ajax
当然,onUpdate 是触发 Ajax 通知给服务器的首要候选,比如当用户重新对需要执行任务的列表或一些其他数据集进行排序时。结合使用 Ajax.Request 和 Sortable.serialize 使实时持久性变得足够简单 −
Of course, onUpdate is a prime candidate for triggering Ajax notifications to the server, for instance when the user reorders a to-do list or some other data set. Combining Ajax.Request and Sortable.serialize makes live persistence simple enough −
<html>
<head>
<title>Sorting Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
<script type = "text/javascript">
window.onload = function() {
Sortable.create('List' ,
{
onUpdate: function() {
new Ajax.Request('file.php',
{
method: "post",
parameters: {data:Sortable.serialize('List')}
}
);
}
}
);
}
</script>
<style type = "text/css">
li { cursor: move; }
ul {
width: 88px;
border: 1px solid blue;
padding: 3px 3px 3px 20px;
}
</style>
</head>
<body>
<p>When you will change the order, AJAX Request
will be made automatically.</p>
<div style = "float:left">
<ul id = "List">
<li id = "List_1">Physics</li>
<li id = "List_2">Chemistry</li>
<li id = "List_3">Maths</li>
<li id = "List_4">Botany</li>
</ul>
</div>
</body>
</html>
Sortable.serialize 会创建一个类似这样的字符串:List[] = 1 & List[] = 2 & List[] = 3 &List[] = 4,其中的数字是列表元素 id 下划线后面的标识符部分。
Sortable.serialize creates a string like: List[] = 1 & List[] = 2 & List[] = 3 &List[] = 4, where the numbers are the identifier parts of the list element ids after the underscore.
接下来我们需要编写 file.php,它会将已发数据作为 parse_str($_POST['data']) 解析,然后你可以执行任何你想做的操作。
Now we need to code file.php, which will parse posted data as parse_str($_POST['data']); and you can do whatever you want to do with this sorted data.
若要详细了解 AJAX,请阅读我们的简单 Ajax Tutorial 。
To learn more about AJAX, please go through our simple Ajax Tutorial.
script.aculo.us - Create Sliders
滑块是在一到多个手柄上放置的细轨,用户可以沿着滑轨拖动这些手柄。
Sliders are thin tracks with one or more handles on them that the user can drag along the track.
滑块的目标是为定义数值提供一种替代的输入方式;滑块表示一个范围,而沿着滑块拖动一个手柄在该范围内的定义一个值。
The goal of a slider is to provide an alternative input method for defining a numerical value; the slider represents a range, and sliding a handle along the track defines a value within this range.
滑块可以采用水平或竖直方向。水平方向时,轨道的左侧通常表示最小值,而竖直方向时,滑块的底部通常是最小值。
Sliders can be in either horizontal or vertical orientation. When horizontal, the left end of the track usually represents the lowest value, while in a vertical orientation, the bottom of the slide is usually the lowest value.
要使用 script.aculo.us 的滑块能力,你需要加载 slider.js 模块以及 prototype.js 模块。因此,用于 script.aculo.us 的最小加载将像这样 −
To use script.aculo.us’s slider capabilities, you’ll need to load the slider.js module along with the prototype.js module. So your minimum loading for script.aculo.us will look like this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load=slider">< /script>
Creating a Slider Control
创建滑块通常是按照元素页面 DOM 中几个现有元素的对象构成的。这里需要两个元素,一个用于句柄,一个用于轨道,如下 −
Creating a slider is, as usual, a matter of constructing a custom object over a few existing elements in your page’s DOM. You’ll need two elements here, one for the handle and one for the track as follows −
new Control.Slider(handle, track [ , options ] );
轨道元素通常是 <div>,句柄元素是轨道元素中的 <div> 或 <span>。两者都可以通过其 id= 或直接 DOM 引用传递,这很常见。
The track element is usually a <div>, and the handle element is a <div> or <span> within the track element. Both can be passed either by their id= or by direct DOM references, as usual.
Sliders Options
创建 Slider 对象时,可以使用以下一个或多个选项。
You can use one or more of the following options while creating your Slider object.
Sr.No |
Option & Description |
1 |
Axis Defines the orientation of the control as horizontal or vertical. The default orientation is horizontal. |
2 |
Range Defines the range of the slider values as an instance of a Prototype ObjectRange instance. Defaults to 0 through 1. |
3 |
Values Defines the discrete set of values that the slider can acquire. If omitted, all values within the range can be set. |
4 |
sliderValue Sets the initial value of the slider. If omitted, the value represented by the leftmost (or top-most) edge of the slider is the initial value. |
5 |
Disabled If true, it creates a slide that is initially disabled. Obviously defaults to false. |
6 |
setValue Will update the slider’s value and thus move the slider handle to the appropriate position. |
7 |
setDisabled Will set the slider to the disabled state (disabled = true). |
8 |
setEnabled Will set the slider to the enabled state (disabled = false). |
可以在选项参数中提供以下回调 −
You can provide the following callbacks in the options parameter −
Sr.No |
Option & Description |
1 |
onSlide Called whenever the Slider is moved by dragging. The called function gets the slider value as its parameter. |
2 |
onChange Called whenever the Slider has finished moving or has had its value changed via the setSlider Value function. The called function gets the slider value as its parameter. |
Sliders Example
<html>
<head>
<title>Sliders Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = slider" ></script>
<script type = "text/javascript">
window.onload = function() {
new Control.Slider('handle1' , 'track1',{
range: $R(1,100), values: [1,25,50,75,100], sliderValue: 1, onChange: function(v){
$('changed').innerHTML = 'Changed Value : '+v;
},
onSlide: function(v) {
$('sliding').innerHTML = 'Sliding Value: '+v;
}
});
new Control.Slider('handle2' , 'track2', {
range: $R(1,100),
axis:'vertical',
sliderValue: 1,
onChange: function(v){
$('changed').innerHTML = 'Changed Value : '+v;
}
onSlide: function(v) {
$('sliding').innerHTML = 'Sliding Value: '+v;
}
});
}
</script>
<style type = "text/css">
h1{ font-size: 1.5em; }
.track {
background-color: #aaa;
position: relative;
height: 0.5em; width: 10em;
cursor: pointer; z-index: 0;
}
.handle {
background-color: red;
position: absolute;
height: 1em; width: 0.25em; top: -0.25em;
cursor: move; z-index: 2;
}
.track.vertical {
width: 0.5em; height: 10em;
}
.track.vertical .handle {
width: 1em; height: 0.25em; top: 0; left: -0.25em;
}
</style>
</head>
<body>
<h1>Simple sliders</h1>
<div id = "track1" class = "track" style = "width: 20em;" >
<div id = "handle1" class = "handle" style = "width: 0.5em;" ></div>
</div>
<p id = "sliding" ></p>
<p id = "changed" ></p>
<div id = "track2" class = "track vertical" style = "position: absolute; left: 25em; top: 3em;" >
<div id = "handle2" class = "handle" style = "height: 0.5em;" ></div>
</div>
</body>
</html>
重点注意事项:
Points to note −
-
You can change the slider image of any slider using CSS. Use CSS properties background-image: url(track.gif) and background-repeat: no-repeat to set the slider image.
-
The range value can be specified using $R(minValue, MaxValue). For example, $R(1, 100).
-
The range value can be specified in terms of specific values. For example values: [1,25,50,75,100]. In this case, the slider would only achieve the discrete values listed as the handle was moved.
-
At any time, the value of the slider can be set under program control by calling the setValue() method of the slider instance, as in: sliderInstance.setValue(50);
这将生成以下结果:
This will produce following result −
script.aculo.us - Auto Completion
默认情况下,script.aculo.us 支持两种自动完成来源 −
Out of the box, script.aculo.us supports two sources for auto-completion −
-
Remote sources (obtained through Ajax),
-
Local sources (string arrays in your web page’s scripts).
根据你计划使用的来源,你将分别实例化 Ajax.Autocompleter 或 Autocompleter.Local。尽管配有特定的选项,但这两个对象共享一组大型功能,并提供统一的用户体验。
Depending on the source you’re planning to use, you’ll instantiate Ajax.Autocompleter or Autocompleter.Local, respectively. Although equipped with specific options, these two objects share a large feature set and provide a uniform user experience.
在构建这些对象时,你始终会将以下四项传递给它们:
There are four things you’ll always pass to these objects while building them −
-
The text field you want to make autocompletable. As usual, you can pass the field itself or the value of its id = attribute.
-
The container for autocompletion choices, which will end up holding a <ul></li> list of options to pick from. Again, pass the element directly or its id =. This element is most often a simple <div>.</p></li>
-
The data source, which will be expressed, depending on the source type, as a JavaScript array of strings or as a URL to the remote source.
-
Finally, the options. As always, they’re provided as a hash of sorts, and both autocompletion objects can make do with no custom option; there are suitable defaults for everything.
为了使用 script.aculo.us 的自动完成功能,你需要加载 controls.js 和 effects.js 模块以及 prototype.js 模块。所以,script.aculo.us 的最小加载量看起来像这样 −
To use script.aculo.us’s autocompletion capabilities, you’ll need to load the controls.js and effects.js modules along with the prototype.js module. So, your minimum loading for script.aculo.us will look like this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
Creating an Ajax Auto-Completer
构建语法如下 −
The construction syntax is as follows −
new Ajax.Autocompleter(element, container, url [ , options ] )
Ajax.Autocompleter 的构造函数接受四个参数 −
The constructor for the Ajax.Autocompleter accepts four parameters −
-
The element name or reference to a text field that is to be populated with a data choice.
-
The element name or reference to a <div> element to be used as a menu of choices by the control.
-
The URL of the server-side resource that will supply the choices.
-
The usual options hash.
Options
创建你的 Ajax.Autocompleter 对象时,你可以使用以下一个或多个选项。
You can use one or more of the following options while creating your Ajax.Autocompleter object.
Sr.No |
Option & Description |
1 |
paramName The name of the query parameter containing the content of the text field that is posted to the server-side resource. Defaults to the name of the text field. |
2 |
minChars Number of characters that must be entered before a server-side request for choices can be fired off. Defaults to 1. |
3 |
Frequency The interval, in seconds, between internal checks to see if a request to the server-side resource should be posted. Defaults to 0.4. |
4 |
Indicator The id or reference to an element to be displayed while a server-side request for choices is underway. If omitted, no element is revealed. |
5 |
Parameters A text string containing extra query parameters to be passed to the server-side resource. |
6 |
updateElement A callback function to be triggered when the user selects one of the choices returned from the server that replaces the internal function that updates the text field with the chosen value. |
7 |
afterUpdateElement A callback function to be triggered after the updateElement function has been executed. |
8 |
Tokens A single text string, or array of text strings that indicate tokens to be used as delimiters to allow multiple elements to be entered into the text field, each of which can be auto-completed individually. |
Example
<html>
<head>
<title>Simple Ajax Auto-completer Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
<script type = "text/javascript">
window.onload = function() {
new Ajax.Autocompleter(
'autoCompleteTextField',
'autoCompleteMenu',
'/script.aculo.us/serverSideScript.php', {}
);
}
</script>
</head>
<body>
<p>Type something in this box and then select suggested option from the list </p>
<div>
<label>Text field:</label>
<input type = "text" id = "autoCompleteTextField"/>
<div id = "autoCompleteMenu"></div>
</div>
</body>
</html>
现在,我们需要服务器端来访问此页面并提供数据源 URL (serverSideScript.php)。您将保持一个完整的逻辑来在此脚本中显示建议。
Now, we need a server side to access this page and serve the data source URL (serverSideScript.php). You will keep a complete logic to display suggestions in this script.
就示例而言,我们在 serverSideScript.php 中保留了一个简单的 HTML 文本。您可以使用 CGI、PHP、Ruby 或任何其他服务器端脚本编写脚本以选择合适的建议,并将它们格式化为 <ul><li>…</li></ul> 形式并将其传递回调用程序。
Just for example, we are keeping a simple HTML text in serverSideScript.php. You can write your script using CGI, PHP, Ruby, or any other server side scripting to choose appropriate suggestions and format them in the form of <ul><li>…</li></ul> and pass them back to the caller program.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ul>
这将生成以下结果:
This will produce following result −
本文档中讨论了不同选项。
with different options discussed in the above table.
Creating a Local Auto-Completer
创建本地自动完成器几乎与我们在前一节中讨论过的创建 Ajax 自动完成器相同。
Creating a local auto-completer is almost identical to creating an Ajax Auto-completer as we have discussed in the previous section.
主要区别在于如何识别用于自动完成的备用数据集。
The major difference lies in how the backing data set to use for auto-completion is identified to the control.
通过 Ajax 自动完成器,我们提供了服务器端资源的 URL,该资源会执行必需的过滤(根据用户输入),并仅返回匹配的数据元素。通过本地自动完成器,我们改为提供数据元素的完整列表(以 JavaScript 字符串数组的形式),并且控件本身在其自己的客户端代码内执行过滤操作。
With an Ajax Auto-completer, we have supplied the URL of a server-side resource that would perform the necessary filtering, given the user input, and return only the data elements that matched. With a Local Autocompleter, we supply the full list of data element instead, as a JavaScript String array, and the control itself performs the filtering operation within its own client code.
整个构造语法实际上如下所示 −
The whole construction syntax is actually as follows −
new Autocompleter.Local(field, container, dataSource [ , options ] );
自动完成器的构造函数接受四个参数:
The constructor for the Autocompleter.Local accepts four parameters −
-
The element name or reference to a text field that is to be populated with a data choice.
-
The element name or reference to a <div> element to be used as a menu of choices by the control
-
For the third parameter, instead of a URL as with the server-assisted auto-completer, we supply a small String array, which contains all of the possible values.
-
The usual options hash.
Options
-
在创建 Autocompleter.Local 对象时,您可以使用以下一个或多个选项。
You can use one or more of the following options while creating your Autocompleter.Local object.
Sr.No |
Option & Description |
1 |
Choices The number of choices to display. Defaults to 10. |
2 |
partialSearch Enables matching at the beginning of words embedded within the completion strings. Defaults to true. |
3 |
fullSearch Enables matching anywhere within the completion strings. Defaults to false. |
4 |
partialChars Defines the number of characters that must be typed before any partial matching is attempted. Defaults to 2. |
5 |
ignoreCase Ignores case when matching. Defaults to true. |
Example
<html>
<head>
<title>Simple Ajax Auto-completer Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
<script type = "text/javascript">
window.onload = function() {
new Autocompleter.Local(
'autoCompleteTextField',
'autoCompleteMenu',
['abcdef','abcdeg','xyzabcefg', 'tybabdefg','acdefg'],
{ignoreCase:false}
);
}
</script>
</head>
<body>
<p>Type something in this box and then select suggested option from the list </p>
<div>
<label>Text field:</label>
<input type = "text" id = "autoCompleteTextField"/>
<div id = "autoCompleteMenu"></div>
</div>
</body>
</html>
显示出来,并且在文本框中键入字符“a”之后,它将显示所有匹配的选项。
When displayed, and after the character 'a' is typed into the text box, it displays all the matching options.
使用我们的在线编译器,更好地理解上面表格中讨论的各种选项的代码。
Use our online compiler for a better understanding of the code with different options discussed in the above table.
这将生成以下结果:
This will produce following result −
script.aculo.us - In-Place Editing
sliderInstance.setValue(50);
In-place editing is one of the hallmarks of Web 2.0.style applications.
inplace 编辑是 Web 2.0.style 应用程序的标志之一。
In-place editing is about taking non-editable content, such as a <p>, <h1>, or <div>, and letting the user edit its contents by simply clicking it.
inplace 编辑是将不可编辑的内容(如 <p>、<h1>或 <div>)转换为可编辑内容,并允许用户通过简单地单击即可编辑内容。
This turns the static element into an editable zone (either singleline or multiline) and pops up submit and cancel buttons (or links, depending on your options) for the user to commit or roll back the modification.
然后,它通过 Ajax 在服务器端同步编辑,并再次使元素变为不可编辑。
It then synchronizes the edit on the server side through Ajax and makes the element non-editable again.
要使用 script.aculo.us 的 inplace 编辑功能,您需要在 prototype.js 模块之外加载 controls.js 和 effects.js 模块。因此,您对 script.aculo.us 的最小加载将如下所示 −
To use script.aculo.us’s in-place editing capabilities, you’ll need to load the controls.js and effects.js modules along with the prototype.js module. So, your minimum loading for script.aculo.us will look like this −
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
Creating an In-Place Text Editor
整个构造语法如下 −
The whole construction syntax is as follows −
new Ajax.InPlaceEditor(element, url [ , options ] )
Ajax.InPlaceEditor 的构造函数接受三个参数 −
The constructor for the Ajax.InPlaceEditor accepts three parameters −
-
The target element can either be a reference to the element itself or the id of the target element.
-
The second parameter to the Ajax.InPlaceEditor specifies the URL of a server-side script that is contacted when an edited value is completed.
-
The usual options hash.
Options
在创建 Ajax.InPlaceEditor 对象时,您可以使用以下一个或多个选项。
You can use one or more of the following options while creating your Ajax.InPlaceEditor object.
Sr.No |
Option & Description |
1 |
okButton A Boolean value indicating whether an "ok" button is to be shown or not. Defaults to true. |
2 |
okText The text to be placed on the ok button. Defaults to "ok". |
3 |
cancelLink A Boolean value indicating whether a cancel link should be displayed. Defaults to true. |
4 |
cancelText The text of the cancel link. Defaults to "cancel". |
5 |
savingText A text string displayed as the value of the control while the save operation (the request initiated by clicking the ok button) is processing. Defaults to "Saving". |
6 |
clickToEditText The text string that appears as the control "tooltip" upon mouse-over. |
7 |
rows The number of rows to appear when the edit control is active. Any number greater than 1 causes a text area element to be used rather than a text field element. Defaults to 1. |
8 |
cols The number of columns when in active mode. If omitted, no column limit is imposed. |
9 |
size Same as cols but only applies when rows is 1. |
10 |
highlightcolor The color to apply to the background of the text element upon mouse-over. Defaults to a pale yellow. |
11 |
highlightendcolor The color to which the highlight color fades to as an effect. Note − support seems to be spotty in some browsers. |
12 |
loadingText The text to appear within the control during a load operation. The default is "Loading". |
13 |
loadTextURL Specifies the URL of a server-side resource to be contacted in order to load the initial value of the editor when it enters active mode. By default, no backend load operation takes place and the initial value is the text of the target element. |
14 |
externalControl An element that is to serve as an "external control" that triggers placing the editor into an active mode. This is useful if you want another button or other element to trigger editing the control. |
15 |
ajaxOptions A hash object that will be passed to the underlying Prototype Ajax object to use as its options hash. |
Callback Options
此外,你可以在 options 参数中使用以下回调函数
Additionally, you can use any of the following callback functions in the options parameter
Sr.No |
Function & Description |
1 |
onComplete A JavaScript function that is called upon successful completion of the save request. The default applies a highlight effect to the editor. |
2 |
onFailure A JavaScript function that is called upon failure of the save request. The default issues an alert showing the failure message. |
3 |
callback A JavaScript function that is called just prior to submitting the save request in order to obtain the query string to be sent to the request. The default function returns a query string equating the query parameter "value" to the value in the text control. |
CSS Styling and DOM id Options
您还可以使用以下选项之一来控制就地编辑器的行为 −
You can also use one the following options to control the behavior of in place editor −
Sr.No |
Option & Description |
1 |
savingClassName The CSS class name applied to the element while the save operation is in progress. This class is applied when the request to the saving URL is made, and is removed when the response is returned. The default value is "inplaceeditor-saving". |
2 |
formClassName The CSS class name applied to the form created to contain the editor element. Defaults to "inplaceeditor-form". |
3 |
formId The id applied to the form created to contain the editor element. |
Example
<html>
<head>
<title>Simple Ajax Auto-completer Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
<script type = "text/javascript">
window.onload = function() {
new Ajax.InPlaceEditor(
'theElement',
'/script.aculo.us/transform.php',
{
formId: 'whatever',
okText: 'Upper me!',
cancelText: 'Never mind'
}
);
}
</script>
</head>
<body>
<p>Click over the "Click me!" text and then change text and click OK.</p>
<p>Try this example with different options.</p>
<div id = "theElement">
Click me!
</div>
</body>
</html>
显示时,单击并编辑文本。这个相当平凡的 PHP 脚本将键为“value”的查询参数的值转换为其等效的大写形式,并将结果写回到响应中。
When displayed, click and edit the text. This rather trivial PHP script converts the value of a query parameter with the key "value" to its uppercase equivalent, and writes the result back to the response.
下面是 transform.php 脚本的内容。
Here is the content of transform.php script.
<?php
if( isset($_REQUEST["value"]) ) {
$str = $_REQUEST["value"];
$str = strtoupper($str);
echo "$str";
}
?>
这将生成以下结果:
This will produce following result −
The In-Place Collection Editor Options
还有一个称为 Ajax.InPlaceCollectionEditor 的对象,它支持就地编辑,并允许您从给定的选项中选择一个值。
There is one more object called Ajax.InPlaceCollectionEditor, which supports in-place editing and gives you the option to select a value from the given options.
整个构造语法如下 −
The whole construction syntax is as follows −
new Ajax.InPlaceCollectionEditor(element, url [ , options ] )
Ajax.InPlaceCollectionEditor 的构造函数接受三个参数 −
The constructor for the Ajax.InPlaceCollectionEditor accepts three parameters −
-
The target element can either be a reference to the element itself or the id of the target element
-
The second parameter to the Ajax.InPlaceEditor specifies the URL of a server-side script that is contacted when an edited value is completed.
-
The usual options hash.
Options
除了添加 collection 选项外,就地收集编辑器的选项列表是从就地文本编辑器继承的选项的子集。
Aside from the addition of the collection option, the list of options for the In-Place Collection Editor is a subset of the options inherited from the In-Place Text Editor.
Sr.No |
Option & Description |
1 |
okButton A Boolean value indicating whether an "ok" button is to be shown or not. Defaults to true. |
2 |
okText The text to be placed on the ok button. Defaults to "ok". |
3 |
cancelLink A Boolean value indicating whether a cancel link should be displayed. Defaults to true. |
4 |
cancelText The text of the cancel link. Defaults to "cancel". |
5 |
savingText A text string displayed as the value of the control while the save operation (the request initiated by clicking the ok button) is processing. Defaults to "Saving". |
6 |
clickToEditText The text string that appears as the control "tooltip" upon mouse-over. |
7 |
Highlightcolor The color to apply to the background of the text element upon mouse-over. Defaults to a pale yellow. |
8 |
Highlightendcolor The color to which the highlight color fades to as an effect. Note − support seems to be spotty in some browsers. |
9 |
Collection An array of items that are to be used to populate the select element options. |
10 |
loadTextUrl Specifies the URL of a server-side resource to be contacted in order to load the initial value of the editor when it enters active mode. By default, no backend load operation takes place and the initial value is the text of the target element. In order for this option to be meaningful, it must return one of the items provided in the collection option to be set as the initial value of the select element. |
11 |
externalControl An element that is to serve as an "external control" that triggers placing the editor into active mode. This is useful if you want another button or other element to trigger editing the control. |
12 |
ajaxOptions A hash object that will be passed to the underlying Prototype Ajax object to use as its options hash. |
Callback Options
此外,你可以在 options 参数中使用以下任何回调函数 −
Additionally, you can use any of the following callback functions in the options parameter −
Sr.No |
Function & Description |
1 |
onComplete A JavaScript function that is called upon successful completion of the save request. The default applies a highlight effect to the editor. |
2 |
onFailure A JavaScript function that is called upon failure of the save request. The default issues an alert showing the failure message. |
CSS Styling and DOM id Options
你还可以使用以下选项之一来控制就地编辑器的行为 −
You can also use one the following options to control the behavior of in-place editor −
Sr.No |
Option & Description |
1 |
savingClassName The CSS class name applied to the element while the save operation is in progress. This class is applied when the request to the saving URL is made, and is removed when the response is returned. The default value is "inplaceeditor-saving". |
2 |
formClassName The CSS class name applied to the form created to contain the editor element. Defaults to "inplaceeditor-form". |
3 |
formId The id applied to the form created to contain the editor element. |
Example
<html>
<head>
<title>Simple Ajax Auto-completer Example</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script type = "text/javascript" src = "/javascript/scriptaculous.js?load = effects,controls"></script>
<script type = "text/javascript">
window.onload = function() {
new Ajax.InPlaceCollectionEditor(
'theElement',
'/script.aculo.us/transform.php',
{
formId: 'whatever',
okText: 'Upper me!',
cancelText: 'Never mind',
collection: ['one','two','three','four','five']
}
);
}
</script>
</head>
<body>
<p>Click over the "Click me!" text and then change text and click OK.</p>
<p>Try this example with different options.</p>
<div id = "theElement">
Click me!
</div>
</body>
</html>
以下是 transform.php 脚本的内容。
Here is the content of the transform.php script.
<?php
if( isset($_REQUEST["value"]) ) {
$str = $_REQUEST["value"];
$str = strtoupper($str);
echo "$str";
}
?>
显示时,单击并选择一个显示的选项。此相当简单的 PHP 脚本将查询参数的值(其中键为“value”)转换为其等效的大写值,并将结果写回响应。
When displayed, click and select one of the displayed options. This rather trivial PHP script converts the value of the query parameter with the key "value" to its uppercase equivalent, and writes the result back to the response.
使用我们的在线编译器,更好地理解上面表格中讨论的各种选项的代码。
Use our online compiler for a better understanding of the code with different options discussed in the above table.
这将生成以下结果:
This will produce following result −