За последние 24 часа нас посетили 16482 программиста и 1671 робот. Сейчас ищут 876 программистов ...

Ошибка в чтении кода

Тема в разделе "JavaScript и AJAX", создана пользователем AngelsPrayer, 4 ноя 2012.

  1. AngelsPrayer

    AngelsPrayer Активный пользователь

    С нами с:
    4 ноя 2012
    Сообщения:
    4
    Симпатии:
    0
    Доброго времени суток!
    Я - новичок к области строения сайтов и потому очень нуждаюсь в помощи людей более опытных и знающих.
    Итак, к сути вопроса:

    Имеется вот такая простенькая галерея на JavaScript
    Код (Text):
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    5. <title>JavaScript Slideshow - TinySlideshow</title>
    6. <link rel="stylesheet" href="gallery_styles.css" />
    7. </head>
    8. <body>
    9.     <ul id="slideshow">
    10.         <li>
    11.             <h3></h3>
    12.             <span>photos/loft1.jpg</span>
    13.             <p></p>
    14.             <img src="thumbnails/loft1.jpg" alt="" />
    15.         </li>
    16.         <li>
    17.             <h3></h3>
    18.             <span>photos/loft2.jpg</span>
    19.             <p></p>
    20.             <img src="thumbnails/loft2.jpg" alt="" />
    21.         </li>
    22.         <li>
    23.             <h3></h3>
    24.             <span>photos/loft3.jpg</span>
    25.             <p></p>
    26.             <img src="thumbnails/loft3.jpg" alt="" />
    27.         </li>
    28.         <li>
    29.             <h3></h3>
    30.             <span>photos/loft4.jpg</span>
    31.             <p></p>
    32.             <img src="thumbnails/loft4.jpg" alt="" />
    33.         </li>
    34.         <li>
    35.             <h3></h3>
    36.             <span>photos/loft5.jpg</span>
    37.             <p></p>
    38.             <img src="thumbnails/loft5.jpg" alt="" />
    39.         </li>
    40.         <li>
    41.             <h3></h3>
    42.             <span>photos/loft6.jpg</span>
    43.             <p></p>
    44.             <img src="thumbnails/loft6.jpg" alt="" />
    45.         </li>
    46.     </ul>
    47.     <div id="wrapper">
    48.         <div id="fullsize">
    49.             <div id="imgprev" class="imgnav" title="Previous Image"></div>
    50.             <div id="imglink"></div>
    51.             <div id="imgnext" class="imgnav" title="Next Image"></div>
    52.             <div id="image"></div>
    53.             <div id="information">
    54.                 <h3></h3>
    55.                 <p></p>
    56.             </div>
    57.         </div>
    58.         <div id="thumbnails">
    59.             <div id="slideleft" title="Slide Left"></div>
    60.             <div id="slidearea">
    61.                 <div id="slider"></div>
    62.             </div>
    63.             <div id="slideright" title="Slide Right"></div>
    64.         </div>
    65.     </div>
    66. <script type="text/javascript" src="gallery_script.js"></script>
    67. <script type="text/javascript">
    68.     //$('slideshow').style.display='block';
    69.     $('wrapper').style.display='block';
    70.     var slideshow=new TINY.slideshow("slideshow");
    71.     window.onload=function(){
    72.         slideshow.auto=true;
    73.         slideshow.speed=5;
    74.         slideshow.link="linkhover";
    75.         slideshow.info="information";
    76.         slideshow.thumbs="slider";
    77.         slideshow.left="slideleft";
    78.         slideshow.right="slideright";
    79.         slideshow.scrollSpeed=4;
    80.         slideshow.spacing=5;
    81.         slideshow.active="#FD7600";
    82.         slideshow.init("slideshow","image","imgprev","imgnext","imglink");
    83.     }
    84. </script>
    85. </body>
    86. </html>
    Как отдельный код она работает замечательно. Но когда я пытаюсь вставить ее в сайт, выпадает табличка с ошибкой "Unable to set value of the property 'display': object is null or undefined"
    Почему такое может быть и как с этим бороться?
    Заранее благодарна за помощь.

    P.S. Следующим вопросом будет: как привязать эту самую галерею к базе данных, но это, наверное, не в этом разделе форума...
     
  2. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    Мне в этом коде не нравится эта строчка
    Обычно указывают '#wrapper'
     
  3. AngelsPrayer

    AngelsPrayer Активный пользователь

    С нами с:
    4 ноя 2012
    Сообщения:
    4
    Симпатии:
    0
    Я попробовала добавить #
    Ошибка остается та же...
    То есть, если запустить этот код как есть, не "переселяя" его на страницу сайта (то есть, оставить независимым файлом), то он прекрасно работает.
     
  4. igordata

    igordata Суперстар
    Команда форума Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.408
    Симпатии:
    1.768
    jQuery надо подключить ещё
     
  5. Your

    Your Старожил

    С нами с:
    2 июл 2011
    Сообщения:
    4.074
    Симпатии:
    7
    Вам стоит открыть документацию...
    С чего вы решили что он должен так работать?

    $('#wrapper') вы понимаете, что-это значит?

    $().

    $('#wrapper').css('display','block');
    $('#wrapper').addClass('display');

    Это вам не this.style.display='block';

    И не document.getElementById('wrapper').style.display='block';

    $(document.getElementById('wrapper')).function();

    Тогда так:
    $('#wrapper')[0].style.display='block';
    $('#wrapper').get(0).style.display='block';

    А вообще почему бы и не:

    $('#wrapper').show();
    $('#wrapper').hide();

    И где вы подключили библиотеку jquery?
     
  6. AngelsPrayer

    AngelsPrayer Активный пользователь

    С нами с:
    4 ноя 2012
    Сообщения:
    4
    Симпатии:
    0
    Ой, ой, ой! Очень много кода для новичка!
    Насколько я понимаю, эта галерея использует скрипты JavaScript, а не библиотеку jQuery.

    Пожалуй, так будет проще:
    1. В первом топике - сам код галереи (собственно, файл index.html).

    2. Это - стили (файл gallery_styles.css)
    Код (Text):
    1. body{
    2. margin:0;
    3. background:#000000;
    4. padding:5px;
    5. font:11px Verdana,Arial;
    6. }
    7.  
    8. #slideshow{
    9. list-style:none;
    10. color:#fff;
    11. }
    12.  
    13. #slideshow span{
    14. display:none;
    15. }
    16.  
    17. #wrapper{
    18. width:506px;
    19. margin:50px auto;
    20. display:none;
    21. }
    22.  
    23. #wrapper *{
    24. margin:0;
    25. padding:0;
    26. }
    27.  
    28. #fullsize{
    29. position:relative;
    30. width:500px;
    31. height:300px;
    32. padding:2px;
    33. border:5px solid #ffffff;
    34. background:#000;
    35. }
    36.  
    37. #information{
    38. position:absolute;
    39. bottom:0;
    40. width:500px;
    41. height:0;
    42. background:#000;
    43. color:#fff;
    44. overflow:hidden;
    45. z-index:200;
    46. opacity:.0;
    47. filter:alpha(opacity=00);
    48. }
    49.  
    50. #information h3{
    51. padding:4px 8px 3px;
    52. font-size:14px;
    53. }
    54.  
    55. #information p{
    56. padding:0 8px 8px;
    57. }
    58.  
    59. #image{
    60. width:500px;
    61. }
    62.  
    63. #image img{
    64. position:absolute;
    65. z-index:25;
    66. width:auto;
    67. }
    68.  
    69. .imgnav{
    70. position:absolute;
    71. width:25%;
    72. height:306px;
    73. cursor:pointer;
    74. z-index:150;
    75. }
    76.  
    77. #imgprev{
    78. left:0;
    79. background:url(images/left.gif) left center no-repeat;
    80. }
    81.  
    82. #imgnext{
    83. right:0;
    84. background:url(images/right.gif) right center no-repeat;
    85. }
    86.  
    87. #imglink{
    88. position:absolute;
    89. height:306px;
    90. width:100%;
    91. z-index:100;
    92. opacity:.4;
    93. filter:alpha(opacity=40);
    94. }
    95.  
    96. .linkhover{
    97. background:url(images/link.gif) center center no-repeat;
    98. }
    99.  
    100. #thumbnails{
    101. width:516px;
    102. margin-top:15px;
    103. }
    104.  
    105. #slideleft{
    106. float:left;
    107. width:30px;
    108. height:30px;
    109. margin-top:25px;
    110. background:url(images/arr_left.png) center center no-repeat;
    111. }
    112.  
    113. #slideleft:hover{
    114. background:url(images/arr_left_s.png) center center no-repeat;
    115. }
    116.  
    117. #slideright{
    118. float:right;
    119. width:30px;
    120. height:30px;
    121. margin-top:25px;
    122. background: url(images/arr_right.png) center center no-repeat;
    123. }
    124.  
    125. #slideright:hover{
    126. background:url(images/arr_right_s.png) center center no-repeat;
    127. }
    128.  
    129. #slidearea{
    130. float:left;
    131. position:relative;
    132. width:447px;
    133. margin-left:5px;
    134. height:83px;
    135. overflow:hidden;
    136. }
    137.  
    138. #slider{
    139. position:absolute;
    140. left:0;
    141. height:83px;
    142. }
    143.  
    144. #slider img{
    145. cursor:pointer;
    146. border:2px solid #ffffff;
    147. padding:2px;
    148. }
    3. Это - код JavaScript (файл gallery_script.js)
    Код (Text):
    1. var TINY={};
    2.  
    3. function $(i){return document.getElementById(i)}
    4. function $$(e,p){p=p||document; return p.getElementsByTagName(e)}
    5.  
    6. TINY.slideshow=function(n){
    7.     this.infoSpeed=this.imgSpeed=this.speed=10;
    8.     this.thumbOpacity=this.navHover=70;
    9.     this.navOpacity=25;
    10.     this.scrollSpeed=5;
    11.     this.letterbox='#000';
    12.     this.n=n;
    13.     this.c=0;
    14.     this.a=[]
    15. };
    16.  
    17. TINY.slideshow.prototype={
    18.     init:function(s,z,b,f,q){
    19.         s=$(s);
    20.         var m=$$('li',s), i=0, w=0;
    21.         this.l=m.length;
    22.         this.q=$(q);
    23.         this.f=$(z);
    24.         this.r=$(this.info);
    25.         this.o=parseInt(TINY.style.val(z,'width'));
    26.         if(this.thumbs){
    27.             var u=$(this.left), r=$(this.right);
    28.             u.onmouseover=new Function('TINY.scroll.init("'+this.thumbs+'",-1,'+this.scrollSpeed+')');
    29.             u.onmouseout=r.onmouseout=new Function('TINY.scroll.cl("'+this.thumbs+'")');
    30.             r.onmouseover=new Function('TINY.scroll.init("'+this.thumbs+'",1,'+this.scrollSpeed+')');
    31.             this.p=$(this.thumbs)
    32.         }
    33.         for(i;i<this.l;i++){
    34.             this.a[i]={};
    35.             var h=m[i], a=this.a[i];
    36.             a.t=$$('h3',h)[0].innerHTML;
    37.             a.d=$$('p',h)[0].innerHTML;
    38.             a.l=$$('a',h)[0]?$$('a',h)[0].href:'';
    39.             a.p=$$('span',h)[0].innerHTML;
    40.             if(this.thumbs){
    41.                 var g=$$('img',h)[0];
    42.                 this.p.appendChild(g);
    43.                 w+=parseInt(g.offsetWidth);
    44.                 if(i!=this.l-1){
    45.                     g.style.marginRight=this.spacing+'px';
    46.                     w+=this.spacing
    47.                 }
    48.                 this.p.style.width=w+'px';
    49.                 g.style.opacity=this.thumbOpacity/100;
    50.                 g.style.filter='alpha(opacity='+this.thumbOpacity+')';
    51.                 g.onmouseover=new Function('TINY.alpha.set(this,100,5)');
    52.                 g.onmouseout=new Function('TINY.alpha.set(this,'+this.thumbOpacity+',5)');
    53.                 g.onclick=new Function(this.n+'.pr('+i+',1)')
    54.             }
    55.         }
    56.         if(b&&f){
    57.             b=$(b);
    58.             f=$(f);
    59.             b.style.opacity=f.style.opacity=this.navOpacity/100;
    60.             b.style.filter=f.style.filter='alpha(opacity='+this.navOpacity+')';
    61.             b.onmouseover=f.onmouseover=new Function('TINY.alpha.set(this,'+this.navHover+',5)');
    62.             b.onmouseout=f.onmouseout=new Function('TINY.alpha.set(this,'+this.navOpacity+',5)');
    63.             b.onclick=new Function(this.n+'.mv(-1,1)');
    64.             f.onclick=new Function(this.n+'.mv(1,1)')
    65.         }
    66.         this.auto?this.is(0,0):this.is(0,1)
    67.     },
    68.     mv:function(d,c){
    69.         var t=this.c+d;
    70.         this.c=t=t<0?this.l-1:t>this.l-1?0:t;
    71.         this.pr(t,c)
    72.     },
    73.     pr:function(t,c){
    74.         clearTimeout(this.lt);
    75.         if(c){
    76.             clearTimeout(this.at)
    77.         }
    78.         this.c=t;
    79.         this.is(t,c)
    80.     },
    81.     is:function(s,c){
    82.         if(this.info){
    83.             TINY.height.set(this.r,1,this.infoSpeed/2,-1)
    84.         }
    85.         var i=new Image();
    86.         i.style.opacity=0;
    87.         i.style.filter='alpha(opacity=0)';
    88.         this.i=i;
    89.         i.onload=new Function(this.n+'.le('+s+','+c+')');
    90.         i.src=this.a[s].p;
    91.         if(this.thumbs){
    92.             var a=$$('img',this.p), l=a.length, x=0;
    93.             for(x;x<l;x++){
    94.                 a[x].style.borderColor=x!=s?'':this.active
    95.             }
    96.         }
    97.     },
    98.     le:function(s,c){
    99.         this.f.appendChild(this.i);
    100.         var w=this.o-parseInt(this.i.offsetWidth);
    101.         if(w>0){
    102.             var l=Math.floor(w/2);
    103.             this.i.style.borderLeft=l+'px solid '+this.letterbox;
    104.             this.i.style.borderRight=(w-l)+'px solid '+this.letterbox
    105.         }
    106.         TINY.alpha.set(this.i,100,this.imgSpeed);
    107.         var n=new Function(this.n+'.nf('+s+')');
    108.         this.lt=setTimeout(n,this.imgSpeed*100);
    109.         if(!c){
    110.             this.at=setTimeout(new Function(this.n+'.mv(1,0)'),this.speed*1000)
    111.         }
    112.         if(this.a[s].l!=''){
    113.             this.q.onclick=new Function('window.location="'+this.a[s].l+'"');
    114.             this.q.onmouseover=new Function('this.className="'+this.link+'"');
    115.             this.q.onmouseout=new Function('this.className=""');
    116.             this.q.style.cursor='pointer'
    117.         }else{
    118.             this.q.onclick=this.q.onmouseover=null;
    119.             this.q.style.cursor='default'
    120.         }
    121.         var m=$$('img',this.f);
    122.         if(m.length>2){
    123.             this.f.removeChild(m[0])
    124.         }
    125.     },
    126.     nf:function(s){
    127.         if(this.info){
    128.             s=this.a[s];
    129.             $$('h3',this.r)[0].innerHTML=s.t;
    130.             $$('p',this.r)[0].innerHTML=s.d;
    131.             this.r.style.height='auto';
    132.             var h=parseInt(this.r.offsetHeight);
    133.             this.r.style.height=0;
    134.             TINY.height.set(this.r,h,this.infoSpeed,0)
    135.         }
    136.     }
    137. };
    138.  
    139. TINY.scroll=function(){
    140.     return{
    141.         init:function(e,d,s){
    142.             e=typeof e=='object'?e:$(e); var p=e.style.left||TINY.style.val(e,'left'); e.style.left=p;
    143.             var l=d==1?parseInt(e.offsetWidth)-parseInt(e.parentNode.offsetWidth):0; e.si=setInterval(function(){TINY.scroll.mv(e,l,d,s)},20)
    144.         },
    145.         mv:function(e,l,d,s){
    146.             var c=parseInt(e.style.left); if(c==l){TINY.scroll.cl(e)}else{var i=Math.abs(l+c); i=i<s?i:s; var n=c-i*d; e.style.left=n+'px'}
    147.         },
    148.         cl:function(e){e=typeof e=='object'?e:$(e); clearInterval(e.si)}
    149.     }
    150. }();
    151.  
    152. TINY.height=function(){
    153.     return{
    154.         set:function(e,h,s,d){
    155.             e=typeof e=='object'?e:$(e); var oh=e.offsetHeight, ho=e.style.height||TINY.style.val(e,'height');
    156.             ho=oh-parseInt(ho); var hd=oh-ho>h?-1:1; clearInterval(e.si); e.si=setInterval(function(){TINY.height.tw(e,h,ho,hd,s)},20)
    157.         },
    158.         tw:function(e,h,ho,hd,s){
    159.             var oh=e.offsetHeight-ho;
    160.             if(oh==h){clearInterval(e.si)}else{if(oh!=h){e.style.height=oh+(Math.ceil(Math.abs(h-oh)/s)*hd)+'px'}}
    161.         }
    162.     }
    163. }();
    164.  
    165. TINY.alpha=function(){
    166.     return{
    167.         set:function(e,a,s){
    168.             e=typeof e=='object'?e:$(e); var o=e.style.opacity||TINY.style.val(e,'opacity'),
    169.             d=a>o*100?1:-1; e.style.opacity=o; clearInterval(e.ai); e.ai=setInterval(function(){TINY.alpha.tw(e,a,d,s)},20)
    170.         },
    171.         tw:function(e,a,d,s){
    172.             var o=Math.round(e.style.opacity*100);
    173.             if(o==a){clearInterval(e.ai)}else{var n=o+Math.ceil(Math.abs(a-o)/s)*d; e.style.opacity=n/100; e.style.filter='alpha(opacity='+n+')'}
    174.         }
    175.     }
    176. }();
    177.  
    178. TINY.style=function(){return{val:function(e,p){e=typeof e=='object'?e:$(e); return e.currentStyle?e.currentStyle[p]:document.defaultView.getComputedStyle(e,null).getPropertyValue(p)}}}();
    Если запустить индекс-файл, галерея будет работать. Никаких дополнительных файлов к ней не прилагается, только папки с самими изображениями.
    Но, если я переписываю код из индекс-файла в страницу сайта (само собой, перенося .css и .js-файлы и картинки в папку сайта и прописав правильные пути к ним), то на сайте появляется сообщение об ошибке...
    Извините, если я задаю глупые вопросы. Я действительно ньюб в этой области, а очень хочется, чтобы все получилось и работало как следует.
     
  7. Your

    Your Старожил

    С нами с:
    2 июл 2011
    Сообщения:
    4.074
    Симпатии:
    7
    А причем тут тогда jquery?
     
  8. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    Проблема еще остается?
    Я запустил твой код, у меня работает...
     
  9. AngelsPrayer

    AngelsPrayer Активный пользователь

    С нами с:
    4 ноя 2012
    Сообщения:
    4
    Симпатии:
    0
    smitt, код работает, как независимый HTML-документ, но выдает ошибку, когда я переписываю его в тело моего сайта.

    Я решила бросить это неблагодарное дело (подгонять чужой код под себя), и сделала галерею сама. Ну, почти сама :)
    Вот теперь возник новый вопрос по jQuery.
    Какая функция jQuery мне нужна, чтобы переключаться между миниатюрами галереи с помощью стрелок "вперед" и "назад"?
    Я смогла анимировать (функция .animate() ) полосу прокрутки изображений, а теперь мне нужно привязать сами изображения к стрелкам и к главной, большой картинке...

    Код .js выглядит вот так:
    Код (Text):
    1.  var x=1;
    2.   $(document).ready(function(){
    3.  
    4.         $(".tmb_slider img").click(function(){
    5.             $("#pic").attr({"src":"gallery/big_thumbs/"+$(this).attr('ct')})
    6.             $(".tmb_slider img").css({
    7.                 "border":"2px solid #FFFFFF"
    8.             })
    9.             $(this).css({
    10.                 "border":"2px solid #FD7600"
    11.             })
    12.         })
    13.  
    14.         function htmSlider(){
    15.         var slideWrap = jQuery('.tmb_slider');
    16.         var nextLink = jQuery('.right_arr');
    17.         var prevLink = jQuery('.left_arr');
    18.    
    19.         var slideWidth = jQuery('.tumbnail').outerWidth();
    20.        
    21.         var newLeftPos = slideWrap.position().left - slideWidth;
    22.        
    23.         nextLink.click(function(){
    24.             if( nextLink.attr('name') == 'next' ) {
    25.                
    26.                 nextLink.removeAttr('name');
    27.  
    28.                 slideWrap.animate({left: newLeftPos}, 500, function(){
    29.                     slideWrap
    30.                         .find('.thumbnail:first')
    31.                         .appendTo(slideWrap)
    32.                         .parent()
    33.                         .css({'left': 0,
    34.                         'margin-left':'10px'});
    35.                 });
    36.                
    37.                 setTimeout(function(){ nextLink.attr('name','next') }, 600);
    38.  
    39.             }
    40.         });
    41.  
    42.         prevLink.click(function(){
    43.             if( prevLink.attr('name') == 'prev' ) {
    44.            
    45.                 prevLink.removeAttr('name');
    46.            
    47.                 slideWrap
    48.                     .css({'left': newLeftPos})
    49.                     .find('.thumbnail:last')
    50.                     .prependTo(slideWrap)
    51.                     .parent()
    52.                     .animate({left: 0}, 500);
    53.  
    54.                 setTimeout(function(){ prevLink.attr('name','prev') }, 600);
    55.             }
    56.         });
    57.  
    58.     }
    59.  
    60.     htmSlider();
    61.  
    62.   })
    А сама галерея - так:
    Код (Text):
    1. <div class="gallery">
    2.                     <div class="b_photo">
    3.                         <img src="gallery/big_thumbs/<?=$gallery[0]['gallery_src'];?>" id="pic" />
    4.                     </div><!-- b_photo -->
    5.  
    6.                     <div class="thumb_box">
    7.                         <div class="left_arr" name="prev"></div>
    8.                         <div class="tmb_slidearea">
    9.                             <div class="tmb_slider">
    10.  
    11.                             <?
    12.                             foreach($gallery as $gkey=>$gval)
    13.                             {
    14.                                 if($gkey == 0)
    15.                                     echo '<img ct="'.$gval['gallery_src'].'" src="gallery/small_thumbs/'.$gval['gallery_src'].'" id="pic'.$gval['gallery_id'].'" class="thumbnail" style="border-color:#FD7600;" />';
    16.                                     else
    17.                                     echo '<img ct="'.$gval['gallery_src'].'" src="gallery/small_thumbs/'.$gval['gallery_src'].'" id="pic'.$gval['gallery_id'].'"class="thumbnail" />';
    18.                                 }
    19.                             ?>
    20.                             </div><!-- tmb_slider -->
    21.                         </div><!-- tmb_slidearea -->
    22.                         <div class="right_arr" name="next"></div>
    23.                         <div style="clear:both;"></div>
    24.                     </div><!-- thumb_box -->
    25.                 </div><!-- gallery -->
    26. <?}?>
     
  10. Your

    Your Старожил

    С нами с:
    2 июл 2011
    Сообщения:
    4.074
    Симпатии:
    7
    Опять вы за свое...
    Причем тут JQuery?

    У вас не подключена библиотека, либо конфликт, откройте $.noConflict();