Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > JavaScript: для новичков > Прошу помощи в разборе скрипта


Автор: klboris 12.1.2010, 16:19
Люди помоготе разобраться в скрипте. Нужно чтобы фреймы менялись автоматически через определенное время. На данный момент меняются только при нажатии на скролеры "вперед" и "назад".
зы. Не пинайте сильно я не очень разбираюсь в java

Скрипт: 
Код

// slide 

var SimpleSlide = new Class({
    initialize: function(container,options) {
        this.container = container;
        this.options = options;
        var automated;
        var direction;
        var hideshow_flag;

        this.hideshow_flag=true;

        if(this.options) this.direction = this.options.direction;
        else this.direction = "forward";

        //    Is it on autorun or manual?
        if (this.direction!="pause")
        {
        if(this.options.auto == "loop" || this.options.auto == "once") {

           this.automated = this.slider.periodical(this.options.time,this,$(this.container));
        } else {
            this.slider($(this.container))
        }
        }
    },

    next: function(type) {
             if(this.options.auto == "loop" || this.options.auto == "once") {
               this.run();
             };
              this.options.type=type;
              this.direction="forward";
              this.slider($(this.container));
     },
    prev: function(type) {
               if(this.options.auto == "loop" || this.options.auto == "once") {
               this.run();
             };
              this.options.type=type;
              this.direction="back";
              this.slider($(this.container));
     },
    pause: function() {
              this.direction="pause";
              this.slider($(this.container));
     },
    run: function() {
           this.direction="forward";
           this.automated = this.slider.periodical(this.options.time,this,$(this.container));
                             },
    slider: function(container) {
        if ((this.options.auto == "once" || this.options.auto == "loop") && this.direction == "run")
        {
           $clear(this.automated);
        }else{
        var child;
        // Get all child nodes to scroll between.
        var children = container.getChildren().getChildren()[0];
        // Run through all child nodes to see if there is a tagged one.
        children.each(function(e) {
            // If there is, make it current child.
            if(e.id == "currentChild") {
                child = e;
            }
           // alert(e.id);
        });
        //alert(this.direction);

            if(!child) {
                // If there isn't, make the first one current child.
                if(this.direction == "forward") {
                    child = children[0].getNext();
                }
                else if(this.direction == "back") {
                    child = container.getChildren()[0].getLast();
                }
            } else {
            // Are we going to the next or previous node?
                if(this.direction == "forward") {
                    var lastElement = container.getChildren()[0].getLast();
                    // Stops the loop at the last element.
                    if(lastElement == child.getNext() && this.options.auto == "once") $clear(this.automated);
                    // Is the current child the last node? Then set the first node as child, otherwise set the next node as child.
                    if(lastElement == child) child = children[0];
                    else child = child.getNext();
                }
                else if(this.direction == "back") {
                    var firstElement = container.getChildren()[0].getFirst();
                    // Stops the loop at the last element.
                    if(firstElement == child.getPrevious() && this.options.auto == "once") $clear(this.automated);
                    // Is the current child the last node? Then set the first node as child, otherwise set the next node as child.
                    if(firstElement == child) child = container.getChildren()[0].getLast();
                    else child = child.getPrevious();}};
                
                
        // Is the child defined?
        if(child && this.direction != "pause") {
            // Which type of slider is defined?
            if(this.options.type == "scroll") this.scroll(container,children,child);
            else if(this.options.type == "fade") this.fade(container,children,child);
            else if(this.options.type == "scrollfade") this.scrollfade(container,children,child);
        }
        if(child && this.direction != "run") {
            // Which type of slider is defined?
            if(this.options.type == "scroll") this.scroll(container,children,child);
            else if(this.options.type == "fade") this.fade(container,children,child);
            else if(this.options.type == "scrollfade") this.scrollfade(container,children,child);
        }
        }
    },

    init_vertical: function() {

       $(this.container).setStyle('position','relative');
       var children = $(this.container).getChildren().getChildren()[0];
       var i;
       var s_h;
       var s_w;
       var b_w;

       b_w=$(this.container).getStyle('border-width').toInt();

       s_h=$(this.container).getSize().size.y-2*b_w;
       s_w=$(this.container).getSize().size.x-2*b_w;

       //s_h=100;
       //s_w=600;

       i=0;
       children.each(function(e) {
          if (i!=0)
          {
            e.id = "currentChild";
            $('currentChild').setStyle('position','relative');
            $('currentChild').setStyle('left',0-s_w*i);
            $('currentChild').setStyle('top',0+s_h*i);
            e.id = "";
          }
          i++;
        });

        children.each(function(e) {
                e.id = "";
            });
     },
    init_horizontal: function() {
 $(this.container).setStyle('position','relative');
       var children = $(this.container).getChildren().getChildren()[0];
       var i;
       var s_h;
       var s_w;
       var b_w;

       b_w=$(this.container).getStyle('border-width').toInt();

       s_h=$(this.container).getSize().size.y-2*b_w;
       s_w=$(this.container).getSize().size.x-2*b_w;

       //s_h=100;
       //s_w=600;

       i=0;
       children.each(function(e) {
          if (i!=0)
          {
            e.id = "currentChild";
            $('currentChild').setStyle('position','relative');
            $('currentChild').setStyle('left',0);
            $('currentChild').setStyle('top',0);
            e.id = "";
          }
          i++;
        });
     },
    scroll: function(container,children,child) {
        // Make it a scroll slide.
        var scroll = new Fx.Scroll(container,{duration: this.options.duration, onComplete: function() {
            // Remove tags from all child nodes.
            children.each(function(e) {
                e.id = "";
            });
            // Tag this child as current
            child.id = "currentChild";
        }}).toElement(child);
    },
    fade: function(container,children,child) {
        // Make it a fade slide
        var fade = new Fx.Style(container,'opacity',{duration: this.options.duration, onComplete: function() {
            new Fx.Scroll(container,{duration: 1,onComplete: function() {
                // Remove tags from all child nodes.
                children.each(function(e) {
                    e.id = "";
                });
                // Tag this child as current
                child.id = "currentChild";
                new Fx.Style(container,'opacity').start(0.01,1);
            }}).toElement(child);
        }})
        fade.start(1,0.01);
    },
    scrollfade: function(container,children,child) {
        // In case you input the miliseconds as a string instead of integer.
        var durationInt = this.options.duration.toInt();
        // Make it a scrollfade slide
        var fade = new Fx.Style(container,'opacity',{duration: (durationInt/2)})
        fade.start(1,0.01).chain(function() {
            fade.start(0.01,1);
        });
        new Fx.Scroll(container,{duration: durationInt, onComplete: function() {
            // Remove tags from all child nodes.
            children.each(function(e) {
                e.id = "";
            });
            // Tag this child as current
            child.id = "currentChild";
        }}).toElement(child);
    },
    hide_and_show_fade:function()
    {
       var fade = new Fx.Style($(this.container),'opacity',{duration: this.options.duration});
       if (this.hideshow_flag)
       {
         fade.start(1,0.01);
       }else
       {
         fade.start(0.01,1);
       }
       this.hideshow_flag=!this.hideshow_flag;
    }
});


Код в странице: 

Код

<script type='text/javascript'>
var  slidebox = new SimpleSlide("SlideBox",{type: "fade", direction: "stop", auto: "loop", time: 3000, duration: 500});
var type_slider='fade';
</script>


Помогите плизз очень нужно  smile 

Автор: firedrago 12.1.2010, 16:24
форумом ошибся -> http://forum.vingrad.ru/forum/Javascript.html

Автор: LSD 12.1.2010, 16:26
Цитата(klboris @  12.1.2010,  16:19 Найти цитируемый пост)
зы. Не пинайте сильно я не очень разбираюсь в java

Начни с того, что выучи разницу между Java и JavaScript.

Автор: klboris 12.1.2010, 16:45
НУ вот просил же не пинать сильно, лучше по делу скажите что нибудь  smile 

Автор: NNaarreekk 12.1.2010, 18:54
Цитата(klboris @  12.1.2010,  18:45 Найти цитируемый пост)
НУ вот просил же не пинать сильно...

Это они не сильно! smile 

по вопросу:
Код

tt=SetTimeout("foo()",3000);

Где foo() надо заменить функцией которая срабатывает когда жмешь на кнопку вперед а 3000 время в милисекундах 3000= 3 сек.

Автор: klboris 12.1.2010, 22:10
Если честно я так и не понял  куда вставлять этот код

Код

tt=SetTimeout("foo()",3000);


Судя по коду

Код

    next: function(type) {
             if(this.options.auto == "loop" || this.options.auto == "once") {
               this.run();
             };
              this.options.type=type;
              this.direction="forward";
              this.slider($(this.container));
     },


то переменная вперед это --> forward

и значит код получается 

Код

tt=SetTimeout("forward()",3000);


а куда вставлять?

зы. Мне легче хостинг на линухе поднять, чем здесь. Объясните плизз на пальцах.  smile 

Автор: NNaarreekk 13.1.2010, 12:19
Как я понял если заменить в коде stop на run то должно само сработать так как у тебя в классе есть функция для поочередной замены.

Попробуй так:

Код

<script type='text/javascript'>
var  slidebox = new SimpleSlide("SlideBox",{type: "fade", direction: "run", auto: "loop", time: 3000, duration: 500});
var type_slider='fade';
</script>

Автор: klboris 13.1.2010, 15:12
Цитата(NNaarreekk @  13.1.2010,  12:19 Найти цитируемый пост)

Как я понял если заменить в коде stop на run то должно само сработать так как у тебя в классе есть функция для поочередной замены.

Попробуй так:
   
<script type='text/javascript'>
var  slidebox = new SimpleSlide("SlideBox",{type: "fade", direction: "run", auto: "loop", time: 3000, duration: 500});
var type_slider='fade';
</script>




нет к сожалению это не так smile . насколько я понимаю функция рун срабатывает только при клики мыши а не автоматом  smile 

Автор: NNaarreekk 13.1.2010, 15:36
Еще так оппробуй, если и так не получится то уже не знаю.
Но точно могу сказать что твой код дает возможность поочередного показывания.
Код

<script type='text/javascript'>
var  slidebox = new SimpleSlide("SlideBox",{type: "fade", direction: "slider", auto: "loop", time: 3000, duration: 500});
var type_slider='fade';
</script>

Автор: klboris 13.1.2010, 20:35
Не хочет собака. 
Про авто я тоже предполагаю там написано:

//    Is it on autorun or manual?

Автор: klboris 14.1.2010, 17:50
Что, так никто и не поможет?  smile  smile 

Пример здесь, вверху сайта http://complexpc.ru/

Автор: 12345c 14.1.2010, 18:31
Цитата(klboris @  12.1.2010,  22:10 Найти цитируемый пост)
и значит код получается код Javascript1:tt=SetTimeout("forward()",3000);
Нет, по тексту - это функция next()

Код

<script type='text/javascript'>
var  slidebox = new SimpleSlide("SlideBox",{type: "fade", direction: "stop", auto: "loop", time: 3000, duration: 500});
var type_slider='fade';
onload = function(){ii=setInterval("slidebox.next",3000);}
</script>
и кнопку "Стоп", если надо, с clearInterval(ii); .

А лучше покажите источник этого кода . Есть вопросы. "new Class" - это значит он для Mootools?
И "auto: "loop"" = это значит, что скипт должен и без того работать, без setInterval?
И тогда вопрос, не забыли ли Вы подключить Mootools по инструкции к скрипту?

Вот нашёл работающий код другого плагина под jQuery: http://www.joshskeen.com/posts/view/16/simpleslide-jquery-plugin

Цитата(NNaarreekk @  12.1.2010,  18:54 Найти цитируемый пост)
SetTimeout(
Ошибка - пишется с мал.буквы.

Добавлено @ 18:40
Да, посмотрел, как вызывается.

Пишите
slidebox.next(type_slider);
Код

<script type='text/javascript'>
var  slidebox = new SimpleSlide("SlideBox",{type: "fade", direction: "stop", auto: "loop", time: 3000, duration: 500});
var type_slider='fade';
onload = function(){ii=setInterval("slidebox.next(type_slider)", 3000);}
</script>
и кнопку "Стоп", если надо, с clearInterval(ii); .
, чтобы не разбираться, почему не работает.

Добавлено @ 18:46
А лучше вместо onload = function(){ii=setInterval("slidebox.next(type_slider)", 3000);} - 

Код

window.addEvent('domready', function() {
  ii=setInterval("slidebox.next(type_slider)", 3000); 
});


====
или вот в чём дело. Отладчик Firebug показывает ошибку:
     
missing ) after argument list
[Break on this error] itleInSystemVar + '" onclick="adhide()" ...предложение!</a></td></tr></table></td><

возможно, она не даёт выполниться скриптам. Уберите рекламу, которая даёт эту ошибку.

Автор: klboris 14.1.2010, 21:16
12345c спасибо огромное,  все работает  smile 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)