Ross Wan's World!

Python, Ajax, PHP and Linux.

Posts Tagged ‘Mootools’

Mootools: toElement 方法

Posted by Ross Wan 于 2009/01/31

toElement 是 Mootools 1.2 里的一个新特性(但并没有在其官方文档里说明)。toElement 只是一个返回 element 对象的方法。当向 $ 传递一个对象时,它会尝试调用对象的 toElement 方法来取得当前 element。

示例

var User = new Class({
    initialize: function(name){
        this.name = name;
    },

    toElement: function(){
        if (!this.element) {
            this.element = new Element('div', {'class': 'user'});
            var avatar = new Element('img', {
                src: '/avatars/' + this.name + '.jpg'

            });
            var description = new Element('div', {
                'class': 'username',
                'text': this.name
            });
            this.element.adopt(avatar, description);
        }
        return this.element;
    }
});

window.addEvent('domready', function(){
    var alice = new User('Alice');
    var bob = new User('Bob');
    $(alice).inject('header', 'after');
    // let's inject bob after alice
    $(bob).inject(alice, 'after');
});
Advertisements

Posted in Ajax, Javascript, Mootools | Tagged: , , | Leave a Comment »

imgslideshow2: 基于 Mootools 的图片幻灯插件

Posted by Ross Wan 于 2009/01/30

之前写了个 jQuery 的图片幻灯插件,但存在不少问题, 例如“疯狂”点击导航按钮会显示不正常。现在用 Mootools 重写了一个 插件。(近来在学 Mootools,学习 Mootools 的源代码)

代码

/* ImgSlideShow, a plugin with mootools. It make the special images slide show.
*
* Licensed under The MIT License
*
* @author mrwlwan#gmail.com
* @date 01/27/2009
* @version 1.0
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*
* Usage:
* var myImgSlideShow = new ImgSlideShow($('mycontainor'));
* or
* var myImgSlideShow = new ImgSlideShow($('mycontainor'), {delay: 50000});
*
* Available methods:
* addImage(imgurl, href, where) add a image element, with the image url, reference url, position inserted.
* pause() pause the animation.
* resume() resume the animation.
*/

var ImgSlideShow = new Class({
   Implements: Options,

   // default settings
   options: {
       'delay': 3000, // set every image pauses time.
       'navBnBgcolor': '#fff',
       'navBnHeightLight': '#f00'
   },

   /* Initializes ImgSlideShow Object.
    *
    * @param {Element} container element which contains images.
    * @param {Object} optional, adjust different settings, like delay time.
    */
   initialize: function(imgContainer, options){
       this.setOptions(options);

       this.imgContainer = imgContainer;   // images container element
       this.imagesArray = imgContainer.getElements('img');     // all images elements array
       this.navBar = null;     // navigator bar element
       this.curentImgEl = null;    // image element displayed currently
       this.timer = null;      // timer, use to be cleared

       this.setImgStyle(this.imagesArray);

       this.imgContainer.setStyles({
           'position': 'relative',
           'overflow': 'hidden'
       });

       this.addNavBar();
       this.action(0);     // animate from the 0 index element.
   },

   /* Set the images' style.
    *
    * @param {Iterable} the image elements array.
    */
   setImgStyle: function(imgs){
       $each(imgs, function(item){
           item.setStyles({
               'visibility': 'hidden',
               'display': 'block',
               'position': 'absolute'
           });
       });
   },

   /* Add a image to the ImgSlideShow Object.
    *
    * @param {String} the imgages url.
    * @param {String} optional, the href url.
    * @param {Integer} optional, Insert the images to the possion of the imagesArray.
    */
   addImage: function(imgurl, href, where){
       var myhref = $pick(href, '#');
       // if the user defined the images in the HTML file, just clone the first image element, and configs it with the user setting.
       if(this.imagesArray.length){
           var aEl = this.imagesArray[0].getParent().clone();
           var newImageEl = aEl.getFirst();
           newImageEl.set('src', imgurl);
           aEl.set('href', myhref);
       }else{
           var newImageEl = new Element('img', {
               'src': imgurl
           });
           var aEl = new Element('a', {
               'href': myhref
           });
           aEl.grab(newImageEl);
       }
       this.setImgStyle([newImageEl]);
       if($chk(where)){
           var pos = parseInt(where);
           if(pos >= 0 && pos < this.imagesArray.length){
               aEl.inject(this.imagesArray[pos].getParent(), 'before');
               this.imagesArray.splice(pos, 0, newImageEl);
               // Refresh the navigator bar buttons.
               this.addNavButton();
               return;
           }
       }
       this.imgContainer.grab(aEl);
       this.imagesArray.push(newImageEl);
       // Refresh the navigator bar buttons.
       this.addNavButton();
   },

   /* Remove the special image element.
    *
    * @param {Integer}
    */
   removeImage: function(index){
       var index = parseInt(index);
       if(!$chk(index) || index < 0 || index >= this.imagesArray.length){
           return;
       }
       this.imagesArray[index].getParent().dispose();
       this.imagesArray.splice(index, 1);
       this.addNavButton();
   },

   /* Add a navigator bar.
    */
   addNavBar: function(){
       var navBar = new Element('div', {
           'id': 'navBar0000'
       });
       navBar.setStyles({
           'position': 'absolute',
           'z-index': 100,
           'right': '5px',
           'bottom': '5px',
           'height': '20px',
           'width': (this.imgContainer.getSize().x - 20),
           'padding-right': 5,
           'overflow': 'hidden'
       });
       navBar.inject(this.imgContainer, 'top');

       this.navBar = navBar;

       this.addNavButton();
   },

   /* Add some buttons to the navigator bar, or refresh the buttons.
    *
    */
   addNavButton: function(){
       if($chk(this.navBar)){
           this.navBar.empty();
       }
       this.imagesArray.each(function(item, index){
           var newBn = new Element('div', {
               'class': 'navbnclass000'
           });
           newBn.setStyles({
               'float': 'right',
               'opacity': 0.5,
               'width': '20px',
               'height': '20px',
               'color': '#000',
               'background-color': this.options['navBnBgcolor'],
               'text-align': 'center',
               'line-height': '20px',
               'margin-right': '2px',
               'cursor': 'pointer',
               'font-weight': 'bold'
           });
           newBn.store('imgEl', item);     // Store the relative image element to the navigator bar button element.
           newBn.store('index', index);    // store the relative index of the image element to the navigator bar button element.
           item.store('bn', newBn);        //Store the relative navigator bar button element to the image element.
           // onClick event, just stop current animation, and resume from the new index.
           newBn.addEvent('click', function(e){
               e.stop();
               var targetEl = e.target;
               targetEl.setStyle('background-color', this.options['navBnHeightLight']);
               this.stop();
               this.action(targetEl.retrieve('index'));
           }.bind(this));
           newBn.appendText(index+1);
           newBn.inject(this.navBar, 'top');
       }, this);
   },

   /* Action the animation. Use recursion algorithm.
    *
    * @param {Integer} animate from the index.
    */
   action: function(index){
       var imagesArrayLength = this.imagesArray.length;
       if(imagesArrayLength<2){
           return;
       }
       if($defined(index) && (index >= imagesArrayLength)){
           index = parseInt(index) % imagesArrayLength;
       }
       this.curentImgEl = this.imagesArray[index];
       this.curentImgEl.retrieve('bn').setStyle('background-color', this.options['navBnHeightLight']);
       this.curentImgEl.set('tween', {
            duration: 500
       }).fade('in').get('tween').chain(function(){
           this.timer = this.subAction.delay(this.options['delay'], this, index + 1);
       }.bind(this));
   },

   /* Used in the action function.
    *
    * @param {Integer} animate from the index.
    */
   subAction: function(index){
       this.curentImgEl.retrieve('bn').setStyle('background-color', this.options['navBnBgcolor']);
       this.curentImgEl.fade('out').get('tween').chain(function(){
           this.action(index);
       }.bind(this));
   },

   /* Stop the animation.
    */
   stop: function(){
       $clear(this.timer);
       this.curentImgEl.get('tween').cancel();
       this.curentImgEl.setStyle('visibility', 'hidden');
       this.curentImgEl.retrieve('bn').setStyle('background-color', this.options['navBnBgcolor']);
   },

   /* Pause the animation.
    *
    */
   pause: function(){
       $clear(this.timer);
       this.curentImgEl.get('tween').cancel();
       this.curentImgEl.setStyles({
           'visibility': 'visible',
           'opacity': 1
       });
   },

   /* Resume the animation.
    */
   resume: function(){
       $clear(this.timer);
       this.curentImgEl.get('tween').cancel();
       this.action(this.curentImgEl.retrieve('bn').retrieve('index'));
   }

});

用法示例

<html>
    <head>
        <title>Demo!</title>
        <script type="text/javascript" src="mootools-1.2.1.js"></script>
        <script type="text/javascript" src="imgslideshow2.js"></script>
        <script type="text/javascript">
            var imgSlideShow = new ImgSlideShow($('imgscontainer'), {delay:3000});
            imgSlideShow.addImage('imgs/2.jpg');
            imgSlideShow.addImage('imgs/3.jpg', '#', 4);
            imgSlideShow.removeImage(3);

           $('pausebn').addEvent('click', function(){
                imgSlideShow.pause();
           });

           $('resumebn').addEvent('click', function(){
                imgSlideShow.resume();
           });
        </script>
    </head>
    <body>
    <div id="imgscontainer">
        <a href='#'><img class='image' src="imgs/1.jpg"/></a>
        <a href='#'><img class='image' src="imgs/2.jpg"/></a>
        <a href='#'><img class='image' src="imgs/3.jpg"/></a>
        <a href='#'><img class='image' src="imgs/4.jpg"/></a>
        <a href='#'><img class='image' src="imgs/5.jpg"/></a>
    </div>
    <div id="bns">
        <button id="pausebn">Pause</button>
        <button id="resumebn">Resume</button>
    </div>
    </body>
</html>

语法

var myImgSlideShow = new ImgSlideShow(element, [, options]);

参数

  • element – 图片的容器对象。
  • options – 可选。如下的可选项

可选项

  • delay – 默认为3000(3秒)。设置图片的显示停留时间。
  • navBnBgcolor – 右下角导航按钮的背景颜色。
  • navBnHeightLight 导航按钮高亮时的背景颜色。

可用方法

  • addImage(imgurl, where) – 在 where 位置上添加一张图片。
  • removeImage(index) – 删除 index 位置上的图片
  • pause() – 暂停动画。
  • resume() – 重新开始动画。

兼容性

支持 IE 6.0+, FF2+, Safari 3.1+, Opera 9.0+

Posted in Ajax, Mootools | Tagged: , , | Leave a Comment »