Mootools自定义方法。
基于Element这个对象,我们添加为其添加新的方法。
整个方法我先写出来:
Elements.implement({
equalize: function(property){ },
setRandom: function(property, min, max){ }
});
通过implement为对象添加新的方法。那我这里以mootools官网的一个例子来说明:
html:
View Code
<p><a id="link" href="#">Execute Example</a></p>
<div id="elements">
<div class="element"></div>
<div class="element"></div>
<div class="element otherElement"></div>
<div class="element otherElement"></div>
</div>
<h3>Code:</h3>
<pre>Elements.implement({
equalize: function(property){
var sum = 0, i, len;
len = i = this.length;
while (i--) sum += this[i].getStyle(property).toInt();
var average = Math.round(sum / len);
i = len;
while (i--) this.tween(property, average);
return this;
},
setRandom: function(property, min, max){
var i = this.length, value;
while (i--){
value = Math.round(min + (max - min) * Math.random());
this[i].tween(property, value);
}
return this;
}
});</pre>
<h3>Usage:</h3>
<pre>myElements.equalize(property);
myElements.setRandom(property, min, max);</pre>
Style:
View Code
#elements {
overflow: hidden;
}
div.element {
width: 100px;
height: 50px;
border: 1px solid black;
background-color: #f9f9f9;
float: left;
margin: 5px;
}
div.otherElement {
height: 20px;
}
pre {
padding: 5px 7px;
margin: 5px 0;
background: #f5f5f5;
border: 1px solid #ddd;
color: #333;
overflow: auto;
font-size: 12px;
}
Script:
View Code
Elements.implement({
equalize: function(property){
var sum = 0, i, len;
len = i = this.length;
while (i--) sum += this[i].getStyle(property).toInt();
alert(sum);
var average = Math.round(sum / len);
i = len;
while (i--) this.tween(property, average);
return this;
},
setRandom: function(property, min, max){
var i = this.length, value;
while (i--){
value = Math.round(min + (max - min) * Math.random());
this[i].tween(property, value);
}
return this;
}
});
window.addEvent('domready', function(){
var els = $$('div.element'), i = false;
$('link').addEvent('click', function(event){
event.stop();
i = !i
if (i) els.equalize('height');
else els.setRandom('height', 30, 150);
});
});
在这个例子里面,我仅仅稍作了些修改。
在equalize这个方法里面,为了满足最新的1.43的版本的规范,我做出了个小的细节的改变。
细心的朋友能够发现原来:while (i--) sum += this[i].getDimensions()[property];
修改后:while (i--) sum += this[i].getStyle(property).toInt();
希望我的说明足够简单易懂,能够让更多的朋友快速的理解mootools。