[JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

[JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Fri Oct 03, 2008 8:51 pm

30 Days of Mootools 1.2 Tutorials : 30天 搞定 Mootools 1.2

30 Days of Mootools 1.2 Tutorials - Day 0 - Thanks Consider: Open, llc
在我們開始30天的Mootools 1.2學習旅程, 我們將先感謝Consider: Open, llc. Consider: Open, llc 將提供本次教學內容, 並許可本站為Mootools的中文讀者翻譯, 翻譯不好的地方, 也請大家提出指教.

30 Days of Mootools 1.2 Tutorials 原文出處: http://www.consideropen.com/blog/tag/30 ... -mootools/

請勿抄襲
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Fri Oct 03, 2008 8:52 pm

30 Days of Mootools 1.2 Tutorials - Day 1 - Intro to the Library
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Tue Nov 04, 2008 10:38 am

30 Days of Mootools 1.2 Tutorials - Day 2 - Selectors
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Tue Nov 04, 2008 10:39 am

30 Days of Mootools 1.2 Tutorials - Day 3 - Intro to Using Arrays
http://www.consideropen.com/blog/2008/0 ... ng-arrays/

原作者: Troy
翻譯: Jui-Yu Tsai

Intro to Using Arrays in Mootools 1.2
介紹如何在Mootools 1.2裡使用陣列

If you haven’t already, be sure and check out yesterday’s tutorial - Day 2 - Selectors
如果錯過上次選取器(selectors)教學的人, 有時間時務必要回去看歐.

In the last tutorial, we looked at selectors, many of which created arrays (a special list that gives you a lot control over the contents). Today, we are going to take a look at how to use arrays to manage DOM elements.

在上次的教學, 教程包含了選取器, 和陣列的新增. 這次, 我們要告訴你如何使用陣列來操控DOM的元件.

The Basics

.each();

.each(); is your best friend when dealing with arrays. It provides an easy way to iterate through a list of elements, applying whatever script logic is necessary. For example, lets say you wanted to call one alert box for every div within a page:

.each(); 是使用陣列(arrays)的最佳夥伴. 它提供了簡易瀏覽元件清單的方式, 並且可以套用任何的函數邏輯. 比如說, 在頁面的每一個div裡呼叫警示視窗(alert box).

With this html, the code above would fire two alert boxes, one for each div.

在以下這段html程式碼中, 上面的函數將會呼叫兩個警示視窗, 一個div一個.

Code: Select all
$$('div').each(function() {
    alert('a div');
});


Code: Select all
<div>One</div>
<div>Two</div>


.each(); doesn’t require you use $$. Another way to create an array (liked we talked about yesterday), is to use .getElements();.

.each(); 的使用並不侷限於$$. 任何可以產生陣列的方式都適用. 像是上次介紹的.getElements();.

Code: Select all
$('body_wrap').getElements('div').each(function() {
    alert('a div');
});


Code: Select all
<div id="body_wrap">
    <div>One</div>
    <div>Two</div>
</div>


Still another way to accomplish the same task is to send the array to a variable, then use .each(); on that variable:

你也可以先把陣列指派到一個變數(variable), 然後再使用.each();.

Code: Select all
//first you declare your variable by saying "var VARIABLE_NAME"
//then you use the equal sign "=" to define what goes in that variable
//in this case, an array of divs
var myArray = $('body_wrap').getElements('div');

//now, you can use that array variable just like an array selector
myArray.each(function() {
    alert('a div');
});


Finally, you are going to want to separate out your function from the selector and .each();. We are going to talk more in depth about how to use functions in tomorrow’s tutorial, but for now, we can create a very simple one like this:

最後, 你可能會問如何把函數(function)與選取器(selector)和.each();分開. 我們將在下次的教學裡介紹如何使用函數, 為了不釣大家胃口, 下面是一個簡易的示範.

Code: Select all
var myArray = $('body_wrap').getElements('div');

//to create a new function, you declare a variable just like before, then name it
//after the equal sign you say "function()" to declare the variable as a function
//finally, you place your function code between { and };
var myFunction = function() {
    alert('a div');
};

//here you just call the function inside .each();.
myArray.each(myFunction);


Note: When you call a function like we did here inside of .each();, you do not put any quotes around the function name.

說明: 如果你要在.each();內呼叫函數, 切記不要在函數名稱加上引號.

Making a Copy of an Array

$A

Mootools provides a way to simply copy an array with the $A function. Lets set up another array with a variable like we did above:

Mootools提供一個簡易複製陣列的函數$A. 讓我們照上述步驟創造一個陣列指派到變數.

Code: Select all
//create your array variable
var myArray = $('body_wrap').getElements('div');


To create a copy of the array:

複製一個陣列.

Code: Select all
//create a new variable, called "myCopy," then assign the copy of "myArray" to your new variable
//新增一個新的變數, 命名為"myCopy", 然後指派(assign)複製好的"myArray"到新增的變數.
var myCopy = $A(myArray );


Now myCopy contains the same elements as myArray.
現在myCopy變數和myArray擁有一樣的元件.

Grab a Specific Element within an Array

.getLast();

.getLast(); will return the last element within an array. First we set up our array:

.getLast();函數將會傳回陣列裡最後的一個元件(element). 首先先創造一個陣列.

Code: Select all
var myArray = $('body_wrap').getElements('div');


Now we can grab the last element within the array:
然後選取陣列內的最後一個元件.

Code: Select all
var lastElement = myArray.getLast();


The variable lastElement now represents the last element within myArray.

變數lastElement將會包含陣列內的最後一個元件.

.getRandom();

Works just like .getLast();, but will get a random element from the array.
跟.getLast();函數功能相似, 這次是傳回陣列內任意的元件而不僅僅是最後一個元件.

Code: Select all
var randomElement = myArray.getRandom();


The variable randomElement is now represents a randomly chosen element within myArray.

變數randomElement將可能是陣列內任意的一個元件.

Add an Element to an Array

.include();

With this method, you can add another item into an array. Simply place the element selector within .include(); and attach it to your array. With the following html setup:

有了這個函數, 你可以輕鬆的新增元件(item)到陣列內. 只要把要新增的元件變數或選取器(selector)放在.include();函數裡, 並附加在原本陣列的尾端. 拿以下html程式碼為例:

Code: Select all
<div id="body_wrap">
    <div>one</div>
    <div>two</div>
    <span id="add_to_array">add to array</span>
</div>


we can create an array like we did before by calling all the divs that are children of ‘body_wrap.’
應用之前介紹的方式, 選取'body_wrap'元件內的div, 並指派到myArray變數.

Code: Select all
var myArray = $('body_wrap').getElements('div');


To add another element to that array, first add the element you want to include to a var, then use the method .include();.

在陣列內新增一個元件, 首先指派你要新增的元件到一變數, 然後使用函數.include();.

Code: Select all
//first add your element to a var
//首先指派你要新增的元件到一變數
var newToArray = $('add_to_array');

//then include the var in the array
//然後把新的變數放至於.include();函數內
myArray.include(newToArray);


Now, the array contains both the divs and the span element.

現在陣列裡應該包含div元件們和span元件.

.combine();

Works just like .include();, except it lets you add an new array to an existing existing array without having to worry about duplicate content. Say we had two arrays from the following html:
使用方法跟.include();一樣, 但這次你可以結合兩個陣列, 且不用擔心有重複的內容. 就拿以下的html程式碼來做範例:

Code: Select all
<div id="body_wrap">
    <div>one</div>
    <div>two</div>
    <span class="class_name">add to array</span>
    <span class="class_name">add to array, also</span>
    <span class="class_name">add to array, too</span>
</div>


We could then build the following two arrays:

從上述的html程式碼中建立兩個陣列.

Code: Select all
//create your array just like we did before
//創造變數myArray並指派body_wrap元件內所有標籤為div的元件.
var myArray= $('body_wrap').getElements('div');

//then create an array from all elements with .class_name
//創造變數newArrayToArray 並指派所有class名成為'class_name'的元件.
var newArrayToArray = $$('.class_name');


Now, we can use .combine(); to combine the two arrays, and the method will deal with any duplicate content so we don’t have to.

然後用函數.combine();結合兩陣列, 此函數將會自行處理重複的元件.

Code: Select all
//then combine newArrayToArray with myArray
myArray.combine(newArrayToArray );


Now myArray contains all the elements from newArraytoArray.

myArray將包含原先的元件和所有原先在newArraytoArray的元件.

Examples

Arrays let you do iterate through a list of items, applying the same chunk of code to each one. In this example, notice the use of “item” as a placeholder for the current element.

陣列提供一個方便瀏覽元件清單的方式, 而且可以把相同的函數單獨的應用在每一個元件上. 以下這個範例, 注意"item"的使用方式, 一個暫存目前瀏覽元件的變數.

Code: Select all
//creates an array of all elements within #body_wrap with the class .class_name
var myArray = $('body_wrap').getElements('.class_name');

//first lets create a new element to add to our array
var addSpan = $('addtoarray');
//now lets create an array to combine with our array
var addMany = $$('.addMany');

//now we can include the new span
myArray.include(addSpan);
//and combine our addMany array with myArray
myArray.combine(addMany);

//create a function to go through each ITEM in the array
var myArrayFunction = function(item) {
   //item now refers to the current element within the array
   item.setStyle('background-color', '#eee');
}

//now you call the myArrayFunction for EACH item within the array
myArray.each(myArrayFunction);


Code: Select all
<div id="body_wrap">
    <div class="class_name">one</div><!-- this has gray background -->
    <div>two</div>
    <div class="class_name">three</div><!-- this has gray background -->
    <span id="addtoarray">add to array</span>  <!-- this has gray background -->
    <br /><span class="addMany">one of many</span>  <!-- this has gray background -->
    <br /><span class="addMany">two of many</span>  <!-- this has gray background -->
</div>


To Learn More…

This tutorial does not begin to cover the wonderful things you can do with arrays, but hopefully it has given you an idea of what Mootools has to offer. To find out more about arrays, take a closer look at:

這次的教學展示了Mootools陣列的基本需知, 並未全方位的包含所有陣列的功能. 如果想要了解更多有關陣列的用法, 請參考以下資訊:


Download a zip with everything you need to get started

Includes a simple html file, the Mootools 1.2 core, an external JavaScript file, a css file and the example above.

此檔案由原文章出處提供. 此檔案幫含了Mootools 1.2 core, 外加的javascript和css檔案, 和以上的範例.

Tomorrow

Tomorrow we will look closer at functions and how to use them in Mootools.

下次我們將探討如何使用Mootools的函數.
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Wed Nov 05, 2008 11:14 am

30 Days of Mootools 1.2 Tutorials - Day 4 - Functions
http://www.consideropen.com/blog/2008/0 ... functions/

原作者: Troy
翻譯: Jui-Yu Tsai

Functions and Mootools 1.2

Welcome to day 4 of the 30 Days of Mootools. If you haven’t already, go check out the previous Mootools Tutorials in the series. Today we’re taking a step back from the Mootools to go over the basics of functions in javascript.

歡迎來到第四天的Mootools教學. 如果有跳過任何之前Mootools的教學, 不要忘記回去補完之前的教學歐. 這次教學我們將專注於javascript的基本函數(function).

Keeping with the Mootools theme however, you should be aware of where to place functions for use with Mootools. Previously we’ve been placing all of our example code within the domready function. When dealing with functions you want to place them outside of the domready loop. Functions aren’t executed until you call them from within the domready.

跟隨著Mootools的作風, 你應該要了解函數在Mootools的放置位置. 在之前的教學, 我們把範例的程式碼放在domready函數裡面. 但在處裡這些函數時, 我們應該把這些函數放在domready函數外. 函數本身將不會自行執行, 而是要等到他們在domready函數裡被呼叫.


Generally it’s a good idea to try and keep as much of your function code outside of the page body all together and call it in through a javascript include. When just monkeying around with code though, I find it easier just to keep everything on the same page. We’re using the following convention for these tutorials:

一般而言, 建議把javascript的程式碼和一般頁面的程式碼區分開來. 但為了便利教學, 整個教學過程將把javascript的程式碼和一般頁面程式碼放在同一頁面. 整個教學將利用以下樣版:

Code: Select all
<script type="text/javascript">
/*
* 函數定義區
* Function definitions go here
*/

window.addEvent('domready', function() {
                /*
                 * 呼叫函數區
                 *Calls to functions go here
                 */
});
</script>


All the examples follow this format, which results in the function being executed when the page loads. They also all have example buttons beneath them which you can press to see the results. This is accomplished through the using Mootools event handlers which we’ll be talking about tomorrow.

將來的範例也將跟隨以上的風格. 函數的結果將在頁面讀取時進行. 範例也提供了範例按鈕提供實際的操作(此功能尚未在本翻譯文章中提供). 這些完全是明天要教的用Mootools事件處理器(event handlers)完成的.

The Basics

There are a few ways to define functions in javascript—since we’re focusing on Mootools we’ll be using their preferred methodology. The example below is about as basic as a function can get. We declare a variable named simple_function and define it as a function:

Javascript提供了幾種不同定義函數(function)的方法 - 既然我們專注的是Mootools, 我們將用Mootools喜好的方法. 以下的範例是最基本的範例. 此範例將定義一個變數, 叫做simple_function, 並將其定義為一函數.

Code: Select all
var simple_function = function(){


Then we add an alert to be run when the function is called:

然後在函數呼叫時啟動上警示視窗(alert).

Code: Select all
alert('This is a simple function');


Finally, we close the function definition with a closing curly bracket:

最後將函數定義用括號關起.

Code: Select all
}


This closing bracket is one of the easiest things to overlook, and can often times be an incredible pain to track down—it’s a good idea to be mildly obsessive about double checking the closing of your function definitions.

結束括號是很簡單的一個動作, 但也常常被遺忘, 一但這種事發生, 整個除蟲的過程將會很不好玩.

It’s all rolled together in the example below. After declaring the function, we’re adding a call to the function to the domready event that will execute on page load. Press the button beneath the example to see the result of calling simple_function(); .

以下範例是結合上述的教學. 在定義完函數之後, 我們在domready事件內呼叫之前定義的含數.

Code: Select all
//Define simple_function as a function
var simple_function = function(){
   alert('This is a simple function');
}

window.addEvent('domready', function() {
        //Call simple_function when the dom(page) is ready
        simple_function();
});


Single Parameter

While having a chunk of code you can easily call from anywhere is useful, it’s even more useful when you can pass it parameters (information) to work with. To use parameters with functions, you need to add a variable name in the parenthesis after function like so:

可以從程式碼中任意的呼叫另外定義的一推程式碼是非常便利的, 如果你能代入參數(parameters)將會變得更有用. 想要使用變數, 你必須在函數(function)的括號內加入變數的名稱.

Code: Select all
var name_of_function = function(name_of_the_parameter){
    /*function code goes here*/
}


Once you’re done, the variable is available inside the function for use. While you can name a parameter pretty much anything you want, it’s a good idea to make your parameter names as descriptive as possible. So for instance, if you were passing a parameter that held the name of a town, calling the parameter town_name would be preferable to something more vague (like user_input).

一但你代入參數, 此參數將可以在函數內部被使用. 你可以任意的對參數命名, 但一個有意義的參數將會讓整個程式碼更簡單被理解. 舉例來說, 如果你要代入一個代表城鎮名的參數, 參數"城鎮名稱(town_name)"將比模糊的"使用者輸入(user_input)"來的容易懂.

In the example below, we’re defining a function that takes a single parameter (called parameter) and sends out an alert containing the parameter. Note that while the first part of the message is surrounded by single quotes, the parameter is not. When you want to use parameters in combination with hardcoded strings, you need to join them together with the + operator as shown below:

下列的範例我們定一了一個可以代入單一參數(parameter)的函數(function), 並且在呼叫此函數時啟動警示視窗來顯示參數內容. 注意第一部分的內容是被單引號括住的, 但參數部分並不需要. 當你要一起使用參數和特定文字(hardcoded strings)時, 你將需要用+運算符號來做連結.

Code: Select all
var single_parameter_function = function(parameter){
        alert('the parameter is : ' + parameter);
}

window.addEvent('domready', function(){
        single_parameter_function('this is a parameter');
});


Multiple Parameters

Javascript doesn’t limit the amount of parameters you can define for a function. It’s generally a good idea to try and keep the number of parameters you pass to a function to a minimum for readability’s sake. Multiple parameters in a function definition are separated by commas, and otherwise behave exactly the same as a single parameter function. The example function below takes two numbers, and places their sum into the variable third_number like so:

Javascript函數沒有參數數目的限制. 但適當的使用參數並且控制在最少的數量將變於程式碼的閱讀. 多個參數將以逗號來做區隔, 其他部分跟單一參數沒有什麼不同. 以下的範例將代入兩個數字, 並把兩數字加總指派到另一個變數.

Code: Select all
var third_number = first_number + second_number;


Then the + operator is used in a slightly different fashion to join the results together into a text string:

+ 運算符號在此將產生不同於連結字串的效果.

Code: Select all
alert(first_number + " plus " + second_number + " equals " + third_number);


While this may seem confusing at first, it’s actually pretty straightforward. If you use + between numbers, you’re adding them together. If you use + between any combination of numbers and strings you’re joining all the input into a single string.

在此, 你可能對+運算符號感到疑惑, 但其實不難理解其中的奧秘. 如果在兩數字中使用+運算符號, 此功能將會是加總. 如果在其中一方為字串, 像是數字和字串, 結果將是字串的連結.

Code: Select all
var two_parameter_function = function(first_number, second_number){
        //Get the sum of first_number and second_number
        var third_number = first_number + second_number;

        //Display the Results
        alert(first_number + " plus " + second_number + " equals " + third_number);
}

window.addEvent('domready', function(){
   two_parameter_function(10, 5);
});


Returning a Value

Displaying the results of a function in an alert can be helpful, but sometimes you’ll want to take the result and use it somewhere else. To accomplish this you need to make use of return within the function. The example below functions pretty much the same as the previous example, except instead of sending out an alert, the script returns the sum of the two numbers here :

以警示視窗顯示結果是很方便的, 但有時你將需要將函數結果應用在其他的程式碼. 要使用函數中的結果在其他地方使用, 你必須在函數中使用傳回(return)語法. 以下範例跟之前的範例大同小異, 只是用傳回兩數字加總來取代警示視窗訊息.

Code: Select all
return third_number;


You’ll notice that we’re doing more in the domready as well. In order to display this value, we’re assigning the functions return value to a parameter named return_value and then displaying an alert.

你可能也注意到我們在domready函數裡也動了手腳. 為了要顯示傳回的數值, 我們用變數(return_value)來接函數傳回的值, 並用警示視窗來顯示.

Code: Select all
var two_parameter_returning_function = function(first_number, second_number){
      var third_number = first_number + second_number;
      return third_number;
}
window.addEvent('domready', function(){
   var return_value = two_parameter_returning_function(10, 5);
   alert("return value is : " + return_value);
});



Functions as Parameters

If you look at the Mootools domready code we’re wrapping things in, you’ll notice that you’re passing a function as a parameter :

仔細探查Mootools domready函數的程式碼部分, 你將會察覺我們把一整個函數(function)代入參數(parameter).

Code: Select all
window.addEvent('domready', function(){
   /*code*/
});


A function that is passed as a parameter like this is referred to as an anonymous function:

像上述程式碼把函數以參數方式代入稱之為"匿名函數(anonymous function)":

Code: Select all
function(){
   /*code*/
}


In the Day 1 comments Boomstix pointed out an alternate method for using the domready without using anonymous functions. Doing so would look something like this :

在第一天的教學, Boomstix的回應中指出有另一種可以不使用匿名函數使用domready的方式. 這種方式將在下列程式碼中呈現:

Code: Select all
//Build the function to be called on domready
var domready_function(){
   /*code*/
}

//Assign the function to the domready event
window.addEvent('domready', domready_function);


I’m not aware of any significant difference between the performance or functionality of the two methods, so I believe this is essentially a stylistic choice. We’re going to be sticking with our method for now, but if anyone out there knows otherwise please let us know.

目前看來, 不論在功能上或效能上, Boomstix的方式並無不同, 原作者相信這只是個人寫程式風格, 所以日後的教學會延用之前的風格, 如果真的有功能或效果上的不同, 請讓我們知道.

Examples

To whet your appetite for tomorrow (and make up for the lack of mootools today), I present a somewhat pointless function to let you change the background color of this page on the fly :

為了提升你學習的慾望(和彌補今天Mootools教學部分不多), 以下將提供一個無關緊要但華麗的範例來讓你改變頁面背景顏色.

Code: Select all
var changeColor = function(){
   //Use get to retrieve the color
   //values from the text boxes
   //( http://docs.mootools.net/Element/Element#Element:get )
   var red   = $('red').get('value');
   var green = $('green').get('value');
   var blue  = $('blue').get('value');

   //Make sure everything is an integer
   //( http://docs.mootools.net/Native/Number#Number:toInt )
   red   = red.toInt();
   green = green.toInt();
   blue  = blue.toInt();

   //Make sure each number is between
   //1 and 255, rounding if needed
   //( http://docs.mootools.net/Native/Number#Number:limit )
   red   = red.limit(1, 255);
   green = green.limit(1, 255);
   blue  = blue.limit(1, 255);

   //Get the Hex Code
   //( http://docs.mootools.net/Native/Array/#Array:rgbToHex )
   var color = [red, green, blue].rgbToHex();

   //Set the Background color of the page
   //( http://docs.mootools.net/Element/Element.Style#Element:setStyle )
   $('body_wrap').setStyle('background', color);

}

var resetColor = function(){
   //Reset the background color to white
   //( http://docs.mootools.net/Element/Element.Style#Element:setStyle )
   $('body_wrap').setStyle('background', '#fff');
}

window.addEvent('domready', function(){
   //Add click events to the buttons (more on this tommorrow)
   //( http://docs.mootools.net/Element/Element.Event#Element:addEvent )
   $('change').addEvent('click', changeColor);
   $('reset').addEvent('click', resetColor);
});


To Learn More…

Download a zip with everything you need to get started

Including the Mootools 1.2 core, an external javascript file, a simple html page and a css file.

此檔案由原文章出處提供. 此檔案幫含了Mootools 1.2 core, 外加的javascript和css檔案, 和以上的範例.

More on Javascript Functions

Quirksmode on Javascript Functions

I’m a little light on good resources for on Javascript functions, if anyone knows of good ones please send them my way

如果你有任何其他更好的Javascript函數資源, 請回應與我們分享.

Example Documentation

Utilities/DomReady
Number.toInt()
Number.limit()
Array.rgbToHex()
Element.setStyle()
Element.addEvent()

Tomorrow’s Mootools 1.2 Tutorial - Events

Check in tomorrow for Day 5 - Events.

別忘了下次的教學 - 事件
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Thu Nov 06, 2008 9:51 am

30 Days of Mootools 1.2 Tutorials - Day 5 - Event Handling
http://www.consideropen.com/blog/2008/0 ... -handling/

Event Handling in Mootools 1.2

原作者: Troy
翻譯: Jui-Yu Tsai

If you haven’t already, be sure and check out the rest of the Mootools 1.2 tutorials in our 30 days series.

如果有跳過任何之前Mootools的教學, 不要忘記回去補完之前的教學歐. 也千萬不要忘記繼續收看我們的30天學好Mootools.

Welcome to Day 5 of 30 Days of Mootools. In the last tutorial we looked at different ways to create and use functions within Mootools 1.2. The next step is to get a grasp on events. Like selectors, events are an essential part of creating an interactive UI. Once you get a hold of an element, you need to then decide what action will cause what effect. Leaving the effects for a later tutorial, lets take a look at that middle step and explore some common events.

歡迎收看30天學會Mootools的第五天學程. 在上次的教學中, 我們學習如何在Mootools 1.2內用不同方式定義和使用函數(functions). 下一步驟將是了解事件(events). 跟選取器(selectors)一樣, 事件(events)也是互動使用者介面中不可缺少的一個要素. 當你在使用元件(element)時, 你可以選擇什麼樣的事件要來產生什麼樣的效果(effect). 特效部份將在未來的教學中提出更深入的探討, 讓我們專注於我們今天的主題"事件", 一起來探討基本的事件.

Single Left Click

The single left click is the most common event in web development. Hyperlinks recognize the click event and take you to another URL. Mootools can recognize the click event on other DOM elements, giving you tremendous flexibility in design and functionality. The first step is to add the click event to an element:

"按滑鼠左鍵一下(single left click)"算是在網頁開發中最基本的事件. 超連結(hyperlinks)收到點擊(click)事件將會把頁面轉到提供的網址. Mootools可以在其他DOM元件中識別出點擊事件, 不在侷限於超連結元件, 這將將強在設計上的彈性和功能性. 第一個步驟, 則是教你如何在元件(element)上加上事件識別的功能:

Code: Select all
//$('id_name') defines the element
//$('id_name') 定義元件
//.addEvent adds the event
//.addEvent 新增事件
//('click') defines the type of event
//('click') 定義事件種類
$('id_name').addEvent('click', function(){
    //put whatever you want to happen on click in here
    //典擊事件所觸發的程式碼
    alert('this element now recognizes the click event');
});


You can accomplish the same thing by separating out the function from .addEvent();.

你也可以利用以下方法把函數從匿名函數中區分出來.

Code: Select all
var clickFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the click event');
}

window.addEvent('domready', function() {
    $('id_name').addEvent('click', clickFunction);
});


Code: Select all
<body>
    <div id="id_name"> <! -- this element now recognizes the click event -->
    </div>
</body>


Note: Just like the click event recognized by hyperlinks, Mootools’ click event actually recognizes “mouse up,” meaning when you let go of the mouse button, not when you push it down. This is to give users a chance to change their mind by dragging the mouse cursor off of the clicked element before letting the mouse button up.

筆記: 其實跟超連結的點擊事件觸發方式一般, Mootools的點擊事件事實上識別滑鼠釋放(mouse up)的動作. 所謂滑鼠釋放是當你放開滑鼠鍵時, 而不是按下或持續按住的那個動作. 因此提供使用者一個反悔的機會, 只要使用者在放開滑鼠按鍵前離開這個元件, 事件就不會被觸發.

Mouse Enter & Mouse Leave

Hyperlinks also recognize “hover” events, where the cursor is over the anchor element. With Mootools, you can add a hover event to other DOM elements. By splitting it up into mouseenter and mouseleave, you get greater control over manipulating the DOM upon users’ actions.

除了點擊事件外, 超連結也能識別空中盤旋(hover)事件, 也就是滑鼠正在超連結上. 在Mootools裡, 你也可以定義空中盤旋(hover)事件在任何DOM元件. 更明確的來說, Mootools把此事件分的更細, 你可以指定是滑鼠進入元件時或滑鼠離開元鍵時, 這提供了開發者更大的彈性.

Just like before, the first thing we have to do is attach an event to an element

像之前一般, 第一步驟是在元件上新增一個事件(把事件跟元件做連結)

Code: Select all
var mouseEnterFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse enter event');
}

window.addEvent('domready', function() {
    $('id_name').addEvent('mouseenter', mouseEnterFunction);
});


Mouseleave works the same way. This event fires when the cursor leaves an element.

滑鼠離開事件使用方法相同. 但此事件只在滑鼠離開元件時觸發.

Code: Select all
var mouseLeaveFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse leave event');
}

window.addEvent('domready', function() {
   $('id_name').addEvent('mouseleave', mouseLeaveFunction);
});


Remove an Event

There are times when you will need to remove an event from an element once it is no longer needed. Removing an event is just as easy as adding one, and even follows a similar structure.

要從元件上移除事件觸發跟新增一觸發事件一樣簡單, 連語法都相似.

Code: Select all
//works just like the previous examples, only replace .addEvent with .removeEvent
$('id_name').removeEvent('mouseleave', mouseLeaveFunction);


Keystrokes in Textarea or Input

Mootools also lets you recognize keystrokes in textareas and inputs. The syntax for this is just like what we saw above:

Mootools還可以在文字輸入區(textarea)識別使用者輸入(input). 在一次的, 語法跟之前一樣:

Code: Select all
var keydownEventFunction = function () {
    alert('This textarea can now recognize keystroke events');
};

window.addEvent('domready', function() {
    $('myTextarea').addEvent('keydown', keydownEventFunction);
});


The above code will recognize any keystroke. To target a particular keystroke, we need to add a parameter and use an if statement:

上述的範例將會識別任何的輸入事件. 如果想要侷限於特定的按鍵, 我們需要輸入參數並使用邏輯區塊(if statement):

Code: Select all
//notice the paramater "event" within the function parenthesis
//注意函數括號內多了一個"event"參數
var keyStrokeEvent = function(event){
    //如果使用者輸入的按鍵是k, 邏輯區塊內的程式碼將會被啟動
    // this says, "if the event key that was pressed is equal to "k," do the following."
    if (event.key == "k") { 
       alert("This tutorial has been brought you by the letter k.")
    };
}

window.addEvent('domready', function() {
    $('myTextarea').addEvent('keydown', keyStrokeEvent);
});


For other controls, such as “shift” and “control,” the syntax is slightly different:

對於其他的輸入控制, 像是 "shift" 和 "control", 語法有些許不同;

Code: Select all
var keyStrokeEvent = function(event){
    // this says, "if the event key that was pressed is "shift," do the following."
    if (event.shift) {
       alert("You pressed shift.")
    };
}

window.addEvent('domready', function() {
    $('myTextarea').addEvent('keydown', keyStrokeEvent);
});


Code: Select all
<div id="body_wrap">
    <textarea id="myInput"></textarea>
</div>


Example

Here are some working examples of the code we went over above:

以下是結合以上範例的實際範例:

Note: try clicking on the single click example, but instead of letting the left click button up, move your cursor off of the block with the button still held down. Notice how it does NOT fire the click event.

筆記: 試著在左鍵點擊範例上按下左鍵, 但不要馬上放開滑鼠按鈕, 先把滑鼠從那個範例元鍵中移出在放開按鈕, 你將會發現事件像先前指出的不會被觸發.

Code: Select all
var keyStrokeEvent = function(event){
    // this says, "if the event key that was pressed is "k," do the following."
    if (event.key == 'k') {
       alert("This Mootorial was brought to you by the letter 'k.'") 
    };
}

var mouseLeaveFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse leave event');
}

var mouseEnterFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the mouse enter event');
}

var clickFunction = function(){
    //put whatever you want to happen in here
    alert('this element now recognizes the click event');
}

window.addEvent('domready', function() {
    $('click').addEvent('click', clickFunction);
    $('enter').addEvent('mouseenter', mouseEnterFunction);
    $('leave').addEvent('mouseleave', mouseLeaveFunction);
    $('keyevent').addEvent('keydown', keyStrokeEvent);
});


Code: Select all
<div id="click" class="block">Single Left Click</div><br />
<div id="enter" class="block">Mouse Enter</div><br />
<div id="leave" class="block">Mouse Leave</div><br />
<textarea id="keyevent">Type the letter 'k'</textarea>


To Learn More…
Download a zip with everything you need to get started

Including the Mootools 1.2 core, an external javascript file, a simple html page and a css file.

此檔案由原文章出處提供. 此檔案幫含了Mootools 1.2 core, 外加的javascript和css檔案, 和以上的範例.

More about Events

Mootools gives you a lot more control over events than we have covered here. To learn more, check out some of the following links:

此篇教學僅包含基本的事件, Mootools提供更多的事件等你去操控. 想學習更深的人, 可以參考以下連結:

[li]Events within the Mootools docs[/li]
[li]Element.Events in the Mootools docs[/li]
[li]Also, read over w3schools’ page on JavaScript events[/li]

Tomorrow’s Tutorial - HTML

Day 6 - Manipulating HTML Elements

第6天課程 - 操控HTML元件
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Fri Nov 07, 2008 9:57 am

30 Days of Mootools 1.2 Tutorials - Day 6 - Manipulating HTML
http://www.consideropen.com/blog/2008/0 ... ting-html/

原作者: Troy
翻譯: Jui-Yu Tsai

Manipulating HTML DOM Elements with Mootools 1.2

If you haven’t already, be sure and check out the rest of the Mootools 1.2 tutorials in our 30 days series.

還沒看之前教學的人要跟上歐, 也不要忘記繼續"收看"30天學會Mootools 1.2

We have already looked at how to select elements within the DOM, how to create arrays, how to create functions, how to attach events to elements and today we are going go further into manipulating HMTL elements. With Mootools 1.2, you can add new elements into an html page, remove elements, and change any style or element parameters, all on the fly.

我們已經知道如何選取DOM的元件, 如何使用陣列和函數, 如何把事件跟元件連結在一起. 今天, 我們要更進一步的來學習如何操控HTML元件. 有了Mootools 1.2, 你可以任意的在HTML網頁上新增移除任何元件, 改變網頁的風格和元件的屬性.

The Basics

.get();

This tool lets you retrieve element properties. Element properties are the various pieces that make up an html element, such as src, value, name, etc. Using .get(); is very simple:

這個函數將方便你讀取元件的屬性(properties). 而一個html元件可能有多個元件屬性所構成, 像是src, value, ...等. 使用.get();格外的簡單:

Code: Select all
//這將會回傳任何html元件(div, a, span...等)id為"id_name"的標籤(tag)
//this will return the html tag (div, a, span...) of the element with the id "id_name"
$('id_name').get('tag');


Code: Select all
<div id="body_wrap">
    <span id="id_name">Element</span> <!-- the above code would return "span" -->
</div>


以上的範例傳回的值將會是"span".

You can use .get() to retrieve more than just html tags:

.get();不只可以用來讀取html的標籤名稱, 也可以取得下列的元件屬性:

* id
* name
* value
* href
* src
* class (will return all classes if the element has multiple)
* text (the text content of an element)
* etc…

.set();

.set(); works just like .get();, except instead of getting a value, it sets a value. This is useful when combined with events and lets you change values after the page has loaded.

.set();的用法跟.get();一樣, 不同點在於此函數是用來設定更改值, 而不僅僅是讀取. 此函數可以和事件觸發一起使用, 像是在頁面讀取後更改頁面內容.

Code: Select all
//this will set the href of #id_name to "http://www.google.com"
//將會更改id為"id_name"元件href的屬性為"http://www.google.com"
$('id_name').set('href', 'http://www.google.com');


Code: Select all
<div id="body_wrap">
    <!-- the above code would change the href url to "http://www.google.com  -->
    <a id="id_name" href="http://www.yahoo.com">Search Engine</a>
</div>


.erase();

With .erase();, you can erase the value of an elements property. It works just like the previous two. Select your element, then choose which property you want to erase.

有了.erase();函數, 你可以移除元件屬性的值. 用法就像之前敘述的兩個函數一般, 選取你的目標元件和要移除的屬性名稱.

Code: Select all
//this will erase the href value of #id_name
//將會移除元件id為"id_name"的href屬性內容.
$('id_name').erase('href');


Code: Select all
<div id="body_wrap">
    <!-- the above code would erase the href url  -->
    <a href="http://www.yahoo.com">Search Engine</a>
</div>


Moving Elements

.inject();

To move an existing element around the page, you can use .inject();. Like the other tools we have looked at, it’s very easy to use and gives you a lot of control over your user interface. To use .inject();, lets first set up a few elements within variables:

你可以利用.inject()函數來移動已定義元件在頁面的位置. 跟其他我們目前看到的函數一樣, 這個函數也是很容易使用, 並且賦予你操控使用者介面的彈性. 在使用.inject();函數前, 讓我們先定義一些變數:

Code: Select all
var elementA = $('elemA');
var elementB = $('elemB');
var elementC = $('elemC');


The above code places this html into variables, making it easy to manipulate with Mootools.

上述程式碼將特定的html元件讀取到變數中, 方便之後Mootools的操控.

Code: Select all
<div id="body_wrap">
    <div id="elemA">A</div>
    <div id="elemB">B</div>
    <div id="elemC">C</div>
</div>


Now, to change the order of the elements, we can use .inject one of four ways. We can inject to the:

.inject();函數提供了四種不同元件移動方式:

* bottom (default)
* top
* before
* after

Bottom and top will place the injected element inside a selected element, in the top or bottom spot. Before and after on the other hand, will inject one element before or after another, but not inside.

下方(bottom)和上方(top)的方式將會把選取元件移置/差入到目標的元件內, 如是"下方"就把元件插入目標元件的最底層, 如是下方則反之. 之前(before)和之後(after)將會把選取元件移置/插入到目標元件的前面或後面, 而不是目標元件裡面.

So, lets change the order to A-C-B. Since we don’t need to inject an element inside another, we can use before or after.

讓我們試著把上述範例元件位置改為A-C-B. 既然我們不需要移動任何元件到其他元件內, 我們只需要用之前或之後的 方式.

Code: Select all
//translates to:  inject element C before element B
//在元件B前插入元件C
elementC.inject(elementB, 'before');

//translates to:  inject element B after element C
//在元件C後插入元件B
elementB.inject(elementC, 'after');


Creating a New Element

new Element

You can use the “new Element” constructor to create a new html element. It’s very much like writing a regular html element, except we will adjust the syntax to make it play well with Mootools:

你可以用"new Element"來新增一個新的html元件. 就像寫html元件一般, 只不過要照著Mootools的語法:

Code: Select all
//first, you name a variable and declare a "new Element"
//首先你命名一個變數, 並指派此變數為一個新元件(new Element).
//then you define which type of element (div, a, span...)
//然後定義此元件的形式/標籤(div, a, span)
var newElementVar = new Element('div', {
    //here you set all the element parameters
    //在此定義所有元件的屬性
    'id': 'id_name',
    'text': 'I am a new div',
    'styles': {
        //here you set all the style parameters
        //在此設定風格的所有屬性
        'width': '200px',
        'height': '200px',
        'background-color': '#eee',
        'float': 'left'
    }
});


Now that you have an element, you can inject it somewhere with the code we learned earlier. Let’s start with the following simple html:

懂了如何新增元件, 你就可以利用之前學的方式來放置新增的元件. 手養了吧, 用以下簡易範例來練習吧:

Code: Select all
<div id="body_wrap">
    <div id="content_id">Some div content</div>
</div>


Now, lets turn #content_id into a variable:

首先先把id為"content_id的元件指派到一變數:

Code: Select all
var bodyWrapVar = $('body_wrap');


Just like we learned before, we can inject the element we created into the current html:

把剛剛學到的在此套用, 把新增的元件置放於html頁面:

Code: Select all
//translates to, "inject newElementVar inside bodyWrapVar, in top position
//把newElementVar插入bodayWrapVar元件裡的最上方
newElementVar.inject(bodyWrapVar , 'top');


The html would end up looking like:

結果將會呈現像下列的程式碼一般:

Code: Select all
<div id="body_wrap">
    <!-- this element was injected to the inside-top -->
    <div id="id_name">I am a new div</div>
    <div id="content_id">Some div content</div>
</div>


Example

For this example, lets create a form that lets you add a new element to your html page. First, lets set up some inputs and a button.

此次的範例將創造一個新增元件到頁面的表格. 首先, 我們需要一些使用者輸入欄位和按鈕.

Code: Select all
<div id="body_wrap">
        ID:  <input id="id_input" name="id" />
        text:  <input id="text_input" name="text" />
        <button id="new_div">create a new div</button>
</div>


Now, lets build the Mootools JavaScript that will let this html form inject a new element into your page. First, let’s add a click event the button and create a function to contain our code:

再來寫一個Mootools的Javascript來使這個表格有插入新增元件的功能. 首先在按鈕新增一個點擊的事件:

Code: Select all
var newDiv = function() {
    //we are going to put our "add a new element" code in here
};

window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});


The next thing we need to figure out is what kind of variables we are going to be dealing with. To use the data in the input forms, we need to .get(); it:

下一步驟就是理解我們需要的變數. 從表格讀取欄位的值, 我們將使用之前教的.get();函數:

Code: Select all
var idValue = $('id_input').get('value');
var textValue = $('text_input').get('value');


Now the variables above, idValue and textValue, contain the value of their respective input forms. Since we want to get the value of the input fields at the time the user clicks the “create a new div” button, we need to place the above code within the newDiv(); function. If we were to get(); the values outside of the function, we would get the values on load, not on click.

以上定義的兩個變數, idValue和textValue, 包含了表格欄位相對的值. 為了在按下"create a new div"按鈕時取得表格欄位的值, 我們將把上述的變數程式碼放入之前自行定義的newDiv();函數. 如果想在函數外取得這些值的話, 我們將把程式碼放入讀取事件中, 而不是點擊事件.

Code: Select all
var newDiv = function() {
    var idValue = $('id_input').get('value');
    var textValue = $('text_input').get('value');
};

window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});


Next, we are going to need to grab our element that we want to inject the new div into:

接下來, 我們將要選取插入新div元件的目標元件

Code: Select all
var newDiv = function() {
    var idValue = $('id_input').get('value');
    var textValue = $('text_input').get('value');
    var bodyWrapVar = $('newElementContainer');
};

window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});


Since we have our input values, we can now create the new element:

我想我們所有需要的東西都有了, 該是新增新元件的時候了:

Code: Select all
var newDiv = function() {
    var idValue = $('id_input').get('value');
    var textValue = $('text_input').get('value');
    var bodyWrapVar = $('newElementContainer');

    var newElementVar = new Element('div', {
        //this sets the id to the value of the input by passing a variable
        //利用之前讀取使用者輸入id值的變數來設定新元件id值
       'id': idValue,
        //this sets the text to the value of the input by passing a variable
        //利用之前讀取使用者輸入text值的變數來設定新元件的html內容
       'html': textValue
    });
};

window.addEvent('domready', function() {
    $('new_div').addEvent('click', newDiv);
});


All we have left is to inject the new element into our page:

最後剩下的就是把新元件插入我們的頁面, 大功告成:

Code: Select all
var newDiv = function() {
   var bodyWrapVar = $('newElementContainer');
   var idValue = $('id_input').get('value');

   var textValue = $('text_input').get('value');

   var newElementVar = new Element('div', {
               'id': idValue,
               'text': textValue
   });

        //translates to, "inject newElementVar inside-top of bodyWrapVar."
   newElementVar.inject(bodyWrapVar, 'top');
};

var removeDiv = function() {
        //this erases the inner html (which is everything inside of the div tags)
   $('newElementContainer').erase('html');
}

window.addEvent('domready', function() {
   $('new_div').addEvent('click', newDiv);
   $('remove_div').addEvent('click', removeDiv);
});


To Learn More…

Make sure to take some time with the Elements section within the Mootools docs:

別忘了花點時間學習Mootools文件內的元件部分歐:

* Element contains most of what we talked about here and a lot more
* Element.style gives you control over style properties (something we will dig into more in another tutorial)
* Element.dimensions contains tools for dealing with position, coordinates and more

Tomorrow’s tutorial

30 Days of Mootools, Day 7 - Setting and Getting Style Properties

30天學好Mootools - 讀取和設定風格(style)屬性
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am

Re: [JS][Moo]Mootools 1.2 教學: 30 Days of Mootools 1.2 Tutorials

Postby mihu » Mon Nov 10, 2008 10:07 am

30 Days of Mootools 1.2 Tutorials - Day 7 - Set and Get Style Properties
http://www.consideropen.com/blog/2008/0 ... roperties/

原作者: Troy
翻譯: Jui-Yu Tsai

Set and Get Style Properties with Mootools 1.2

If you haven’t already, be sure and check out the rest of the Mootools 1.2 tutorials in our 30 days series.

Welcome to day 7 of 30 Days of Mootools. Today we are going to look at how to manipulate styles with Mootools 1.2 Combined with what we have learned in the last few tutorials, this will give you a lot of control over your UI. Dealing with styles is very simple, but there are going to be a few twists today. For example, we are going introduce the idea of a key/value object. We are also going to pass variables outside of the domready, liked we learned how to do in the functions tutorial. From here on out, the tutorials are going to slowly ramp up in complexity to introduce a few necessary programming concepts. If you are new to JavaScript or learning Mootools for the first time, be sure you understand the previous articles and feel free to ask us any questions you may have.

The Basics

.setStyle();

This function lets you set a style property of an element. We have used this one before in some of the previous examples. All you do is tack .setStyle(); onto the end of your selector and it will change the style property of a single element or an array

.setStyle();函數提供更變元件風格屬性的方法. 這個函數可能在先前的範例中已經出現過. 把此函數附加於選取器之後, 你將可以利用此函數改變一個或多個元件風格.

Code: Select all
//define your selector
//add .setStyle
//define the style property and the value
$('body_wrap').setStyle('background-color', '#eeeeee');
$$('.class_name').setStyle('background-color', '#eeeeee');


Code: Select all
<div id="body_wrap">
    <div class="class_name"></div>
    <div class="class_name"></div>
    <div class="class_name"></div>
    <div class="class_name"></div>
</div>


.getStyle();

Again, this does pretty much what it says. .getStyle(); will return the value of a style property of an element.

此函數功能就像字面上的意思, 回傳元件指定的風格值.

Code: Select all
//first, set up your variable to hold the style value
var styleValue = $('body_wrap').getStyle('background-color');


If we ran this code on the example above, it would return ‘#eeeeee’ to the variable styleValue.

以上範例將回傳'#eeeeee'到變數"styleValue".

Setting and Getting Multiple Style Properties

.setStyles();

.setStyles(), as you can imagine, lets you set multiple style properties onto a single element or an array. The syntax for .setStyles(); is a little bit different so that it can allow for multiple style properties.

沒錯, 就跟你想的一樣, .setStyles();可以對一個或多個元件一次更改多個風格屬性. 此函數語法跟先前的.setStyle();些許不同, 以便允許更改多個風格屬性.

Code: Select all
//start out by creating your selector, then add .setStyles({
$('body_wrap').setStyles({
    //the pattern to follow is 'property': 'value',
    'width': '1000px',
    'height': '1000px',
    //IMPORTANT: there is NO COMMA after the last property
    //will mess up cross browser if you leave the comma
    'background-color': '#eeeeee'
});


Note: You do not actually need the ’single quotes’ around the property selector unless there is a ‘-’ in the property, like in ‘background-color,’ but to keep it simple, its easier to remember to put them on every property selector.

筆記: 在許取風格時, 單引號不是必須的, 除非在屬性名稱內有"-"符號, 比如說, 'background-color'; 但是為了簡單和好記, 我們決定在每個風格屬性上加上單引號.

Also Note: There is more flexibility with the property value (like ‘100px’ or ‘#eeeeee’). Aside from strings (just a series of characters, but we will get into that deeper in a later tutorial), you can also pass it numbers without quotes (which will eventually be interpreted as px in most cases) and variables:

筆記: 對於風格屬性的值(像是 '100px', '#eeeeee'). 除了字串以外(一連串的字母, 之後會深入這部分), 你還可以指派無引號的數字值(大多的時候會自動被解釋為px)或變數.

Code: Select all
//this passes the variable firstBackgroundColor the STRING '#eeeeee'
var firstBackgroundColor = '#eeeeee';

//you can pass a variable to another variable,
//making backgroundColor equal the string '#eeeeee'
var backgroundColor = firstBackgroundColor;

//this passes the variable divWidth the NUMBER 500
var divWidth = 500;

$('body_wrap').setStyles({
    //in this case, variables are words without quotes around them
    'width': divWidth,
    //numbers are, well, numbers without quotes around them
    'height': 1000,
    //another variable
    'background-color': backgroundColor,
    //strings are a series of characters inside 'single quotes'
    'color': 'black'
});


.getStyles();

This lets you get multiple styles in one fell swoop. This works just a little bit different than what we saw above as it holds multiple SETS of data, a key (the property) and a value (the property value). This set of data is called an OBJECT and .getStyles(); makes it very easy to throw multiple styles into these objects and keeps it simple to get them back.

此函數讓你一次讀取多個風格屬性. 這次, 這個函數和這次之前介紹的函數有些不同. 此函數將會握有多組的數據(一個索引(風格屬性名稱), 和一個值(風格屬性值)). 每組數據將為一個物件(object). .getStyles();函數將便於讀取多個風格屬性並指派於此物件.

Code: Select all
//first define a variable for your object
//next create a selector
//then add .getStyles to your selector
//finally create a comma separated list of style properties
//be sure to keep the properties inside single quotes
var bodyStyles = $('body_wrap').getStyles('width', 'height', 'background-color');

//first we create a new variable to hold the property value
//then we call a particular property by its key, which in this case, is the property name
//put the property name inside of [brackets]
//and be sure to put 'single quotes' around the property key
var bgStyle = bodyStyles['background-color'];


If we have the following styles in our CSS file:

以下為我們的css風格內容

Code: Select all
#body_wrap {
    width: 1000px;
    height: 1000px;
    background-color: #eeeeee;
}


then bgStyle will contain the value ‘#eeeeee.’

以上的範例變數"bgStyle"將會傳回值"#eeeeee".

Note: when you want to get a single property from your object of styles, first state the object variable (in this case, bodyStyles), then use brackets and single quotes (['']), finally place the property key (such as width or background-color). That’s all there is to it.

註記: 當你試著讀取風格物件的單一屬性時, 首先要先取得物件變數(此範例為bodyStyles), 然後在使用方括弧和單引號, 並把屬性名稱(像是'width'或'background-color')置入單引號內為索引. 就這樣大功告成.

Example

In this example, we are going to use a few of the methods we learned above to get and set styles. More than the use of style property manipulation, please note the structure itself. To separate our functions from our domready, we need to pass those functions some variables that are set within the domready event. We accomplish this through adding a parameter to the function inside the domready, then referring to that variable outside of the domready. Notice that the click events use anonymous functions - this lets us pass the variables from the domready event to the functions that are outside. Don’t worry if this doesn’t make sense on your first read through, the example below should make it more clear.

此範例我們將使用這次所學的來讀取和設定風格屬性. 除了了解如何操控風格屬性, 也別忘了學習整體的架構. 為了從domready函數中移出定義的函數, 我們將需要從domready函數中的變數傳出給定義的函數使用. 為了要傳變數到domready外定義的函數, 我們必須在要呼叫的函數中代入參數, 以便於domready函數外的領域讀取此
注意點擊事件如何使用匿名函數指派變數給domready外的函數使用. 如果無法從這段文字中理解, 不妨這著了解下方的範例, 應該會比文字敘述來的容易理解.

Code: Select all
//here are the functions

//notice that this function has a parameter "bgColor"
//this is passed from within the domready event
var seeBgColor = function(bgColor) {
   alert(bgColor);
}

var seeBorderColor = function(borderColor) {
   alert(borderColor);
}

//we pass in playDiv giving the function access to the element
//also keeps us from having to use the selector repeatedly
//very useful when dealing with complicated selectors
var seeDivWidth = function(playDiv) {
        //we are getting the style again,
        //separate from the getStyles we use in the domready
        //because we want the current value
        //this keeps the width alert accurate
        //even when it has been changed after the domready event has passed
   var currentDivWidth = playDiv.getStyle('width');
   alert(currentDivWidth);
}

var seeDivHeight = function(playDiv) {
   var currentDivHeight = playDiv.getStyle('height');
   alert(currentDivHeight);
}

var setDivWidth = function(playDiv) {
   playDiv.setStyle('width', '50px');
}

var setDivHeight = function(playDiv) {
   playDiv.setStyle('height', '50px');
}

//note that this parameter can be named anything at this level
//and it will be passed whatever value/element/what-have-you
//that is placed within the () of the function within the domready
var resetSIze = function(foo) {
   foo.setStyles({
      'height': 200,
      'width': 200
   });
}

window.addEvent('domready', function() {
        //since we use this selector a lot, it saves us writing time to pass it to a var
   var playDiv = $('playstyles');

        //here we create an object of several style properties
   var bodyStyles = playDiv.getStyles('background-color', 'border-bottom-color');

        //you can retrieve a style by calling the key and passing the result to a var

   var bgColor = bodyStyles['background-color'];

        //here we use an anonymous function so we can pass a parameter outside the domready event
   $('bgcolor').addEvent('click', function(){
      seeBgColor(bgColor);
   });

   $('border_color').addEvent('click', function(){
                //instead of passing the style parameter to a variable,
                //you can call it directly here in this alert
      seeBorderColor(bodyStyles['border-bottom-color']);
   });

   $('div_width').addEvent('click', function(){
      seeDivWidth(playDiv);
   });

   $('div_height').addEvent('click', function(){
      seeDivHeight(playDiv);
   });

   $('set_width').addEvent('click', function(){
      setDivWidth(playDiv);
   });

   $('set_height').addEvent('click', function(){
      setDivHeight(playDiv);
   });

   $('reset').addEvent('click', function(){
      resetSIze(playDiv);
   });
});


heres the html

這是html程式碼

Code: Select all
<div id="playstyles"> </div>
    <br />
    <button id="bgcolor">See background-color</button>
    <button id="border_color">See border-bottom-color</button><br /><br />
    <button id="div_width">See width</button>
    <button id="div_height">See height</button><br /><br />
    <button id="set_width">Set weight to 50px</button>
    <button id="set_height">Set height to 50px</button><br /><br />
    <button id="reset">Reset size</button>


heres the css

這是css風格內容

Code: Select all
#playstyles {
   width: 200px
   height: 200px
   background-color: #eeeeee
   border: 3px solid #dd97a1
}


Download a zip with everything you need to get started

Including the Mootools 1.2 core, an external javascript file, a simple html page and a css file.

此檔案由原文章出處提供. 此檔案幫含了Mootools 1.2 core, 外加的javascript和css檔案, 和以上的範例.

More about styles

To learn more about styles, take a look over the Element.Style docs.

想要學習更多有關於風格的部分, 請參閱官網的Element.Style文件.

Tomorrow’s Mootools 1.2 Tutorial - Input Filtering Part 1 (Numbers)

Check in tomorrow for Day 8 - Input Filtering Part 1 (Numbers).

別忘了下次第八天的課程 - 使用者輸入過濾 第一部分 (數字篇)
User avatar
mihu
 
Posts: 183
Joined: Thu Jan 10, 2008 10:44 am


Return to Javascript

Who is online

Users browsing this forum: No registered users and 1 guest

cron