关于Mootools, 这次我们说说他的event。对于as的朋友来说, 它是最熟悉不过的。
我们废话不说,速度进入实例。
显示如下:
Magic Words to type: hello, moo, pizza, burn, delayed (this last one will fire after 1 second).
正如上面显示,我们计划要开发的是当用户输入以上几个单词的时候,便会触发某些事件。
js部分:
window.addEvent(\'domready\', function() {
var textarea = $(\'myTextarea\'), log = $(\'log\').setStyle(\'opacity\', 0);
// We define the highlight morph we\'re going to
// use when firing an event
var highlight = new Fx.Morph(log, {
duration: 1500,
link: \'cancel\',
transition: \'quad:out\'
});
// Here we start adding events to textarea.
// Note that \'focus\' and \'keyup\' are native events, while \'burn\'
// is a custom one we\'ve made
textarea.addEvents({
focus: function() {
// When focusing, if the textarea contains value "Type here", we
// simply clear it.
if (textarea.value.contains(\'Type here\')) textarea.set(\'value\', \'\');
},
keyup: function() {
// When user keyups we check if there are any of the magic words.
// If yes, we fire our custom event burn with a different text for each one.
if (textarea.value.contains(\'hello\')) textarea.fireEvent(\'burn\', \'hello world!\');
else if (textarea.value.contains(\'moo\')) textarea.fireEvent(\'burn\', \'mootools!\');
else if (textarea.value.contains(\'pizza\')) textarea.fireEvent(\'burn\', \'Italy!\');
else if (textarea.value.contains(\'burn\')) textarea.fireEvent(\'burn\', \'fireEvent\');
// note that in case of \'delayed\', we are firing the event 1 second late.
else if (textarea.value.contains(\'delayed\')) textarea.fireEvent(\'burn\', "I\'m a bit late!", 1000);
},
burn: function(text) {
// When the textarea contains one of the magic words
// we reset textarea value and set the log with text
textarea.set(\'value\', \'\');
log.set(\'html\', text);
// then we start the highlight morphing
highlight.start({
backgroundColor: [\'#fff36f\', \'#fff\'],
opacity: [1, 0]
});
}
});
});
有些朋友一看,觉得怎么这么多?那么为了简易,结构更加清晰,我给大家提炼一下:
window.addEvent(\'domready\', function() {
var textarea = $(\'myTextarea\'), log = $(\'log\').setStyle(\'opacity\', 0);
// 定义Fx.Morph
var highlight = new Fx.Morph(log, { 具体内容 });
//给textarea侦听事件
textarea.addEvents({
//定义focus事件
focus: function() {具体内容},
//定义keyup事件
keyup: function() {具体内容},
//定义burn事件
burn: function(text) {具体内容}
});
});
其中的burn就是个自定义事件,什么时候触发呢?看这里:textarea.value.contains(\'hello\') textarea.fireEvent(\'burn\', \'hello world!\');
说到这里,大伙应该明白了吧。欢迎更多交流。