28 января 2008 ~ 4204 Комментария

Горизонтальный скроллинг в блоке

slider2
Горизонтальный скроллинг это очень оригинальный прием, а именно оригинальность одна из главных составляющих успеха любого проекта.

Как это работает?

Создается блок(Container) с ограничением размера, в Container помещается блок большего размера(Slider) в котором находятся блоки с контентом(Section).

В блоке Container мы будем видеть только лишь часть блока Slider, как показано на рисунке ниже.

See Spot Run trailer

slider1

При определенном действии блок Slidera сдвигается и тем самым его видимая часть меняется, как это показано на рисунке ниже.

slider3

Думаю теперь все и всем понятно :)

Реализация

Все операции с движением блока Slider будет происходить с помощь всем известной javascript библиотеки mootools.

HTML код очень простой. Сначало подключим и настроим библиотеку mootools вставив код данный ниже между тегами head.


<script type="text/javascript" src="mootools.svn.js"></script>
<script type="text/javascript">
window.addEvent('domready', function(){
var scroll = new Scroller('container', {area: 100, velocity:1});
$('container').addEvent('mouseover', scroll.start.bind(scroll));
$('container').addEvent('mouseout', scroll.stop.bind(scroll));
});
</script>

Далее создадим все необходимые блоки.


<div id="container">
  <div class="slider">
    <div class="section">section 1 content</div>
    <div class="section">section 2 content</div>
    <div class="section">section 3 content</div>
    <div class="section">section 4 content</div>
    <div class="section">section 5 content</div>
  </div>
</div>

Теперь осталось только оформить все это дело с помощью css


#container{
width: 780px; height: 440px;
border: 8px solid #FFF;
overflow: auto;
margin: 0 auto;
overflow-x: hidden;
overflow-y: hidden;
} 

.slider{
width: 2000px; height: 400px;
padding: 20px;
background: #CCCCCC;
}

 .section{
margin:0; width:220px;
float:left;
margin-right:50px;
}

Все! Готово ^_^

Посмотреть пример

Скачать пример

По мотивам:

http://woork.blogspot.com/2008/03/using-css-and-mootools-to-simulate.html

4204 Комментария для “Горизонтальный скроллинг в блоке”

  1. warkord 28 марта 2008 at 15:36 Permalink

    В firefox 2.0.0.9 в обратную сторону очень тормозно прокручивается. А так интересно, спасибо.

  2. Bum3r 28 марта 2008 at 17:01 Permalink

    Супер.
    warkord, а у меня нормально прокручиваеться и в нормальную сторону.
    FireFox 2.0.0.13

  3. WebApelsin 28 марта 2008 at 17:37 Permalink

    Можно ли подобного эффекта достичь без использования Mootools? Или хотя бы с помощью jQuery…

  4. Я собственной персоной 28 марта 2008 at 19:57 Permalink

    WebApelsin, хм, понятия не имею :/

  5. Виктор 29 марта 2008 at 19:44 Permalink

    ИМХО, syntaxhighlighter sucks, highlight.js от Ивана Сагалаева ( http://softwaremaniacs.org/soft/highlight ) рулит. ;-)

  6. Я собственной персоной 29 марта 2008 at 20:15 Permalink

    Действительно хорошая вещь, искреннее спасибо Виктор ;)

  7. Иван Сагалаев 30 марта 2008 at 19:22 Permalink

    Кстати, у вас в последнем куске кода (CSS) нет закрывающей «}», поэтому highlight.js отказывается считать это CSS’ом и не расцвечивает.

  8. Я собственной персоной 30 марта 2008 at 19:49 Permalink

    Кстати, у вас в последнем куске кода (CSS) нет закрывающей «}», поэтому highlight.js отказывается считать это CSS’ом и не расцвечивает.

    Спасибо, после моего глобального апдейта на скорую руку все подгонял и одной скобочки недосчитался :)

  9. Антон 31 марта 2008 at 20:37 Permalink

    Спасибо! Очень круто!..)))

  10. Иван 3 апреля 2008 at 21:38 Permalink

    Из-за Mootools.svn.js размером 183Кб пример открывался немеренное количество времени. Нафиг такие эффекты. Не перевелись еще узкие каналы на Руси :(

  11. Иван 3 апреля 2008 at 21:40 Permalink

    > Написал Иван 28.03.08 в 14:11
    И написал я это 03.04.08 в 17:40 :)
    Кстати, у всех комментов неправильное время стоит

  12. Я собственной персоной 3 апреля 2008 at 22:13 Permalink

    > Написал Иван 28.03.08 в 14:11
    И написал я это 03.04.08 в 17:40 :)
    Кстати, у всех комментов неправильное время стоит

    Нет нет нет! Все правильно, в моем блоге мы будем жить по моим законам и по моему времени :-)

  13. Я собственной персоной 3 апреля 2008 at 22:25 Permalink

    Только вот почему то, время комментариев не моё 0_о и оно мне не подвластно!

  14. Я собственной персоной 3 апреля 2008 at 22:29 Permalink

    Я исказил время и пространство! *Злобный смех*
    Наладил в смысле.

  15. Евгений 11 апреля 2008 at 0:50 Permalink

    А как сделать появляющиеся стрелочки (например как на http://inside.nile.ru/#years-2008/ – работает в Мозилле и не работает в ИЕ)? А то непонятно как нужно крутить если об этом не писать специально..

  16. Стас 16 апреля 2008 at 13:30 Permalink

    Это просто шедеврально! Уже только этот пост достаточен для добавления блога в rss!

  17. ilyt 14 мая 2008 at 19:43 Permalink

    интересно а можно ли сделать чтобы блок открывался не справа, а по центру?..

  18. Flyer 10 июля 2008 at 23:54 Permalink

    как сделать, чтобы прокрутка осуществлялась при нажатии на ссылки, а не при наведении на область?

  19. Иван 7 октября 2008 at 18:52 Permalink

    блин классная штука она мне очень пригодилась а если бы еще прокручивать колёсиком мышки то ваще выло бы супер!!!

  20. Иван 7 октября 2008 at 18:55 Permalink

    а на счет веса скриптового файла 180кб который из него можно каменты поудолять при желании )

  21. Павел 19 октября 2008 at 1:22 Permalink

    столкнулся с такой проблемой как прокруткой в firefox,
    т.е при прокрутке при переходе с одного курсора с одного элемента section на другой происходит остановка прокрутки, (только в firefox)
    на представленном примере эт тоже есть,
    * версии ff перепробовал разные,
    как решить ?

  22. Павел 19 октября 2008 at 1:42 Permalink

    столкнулся с такой проблемой как прокруткой в firefox,
    т.е при прокрутке при переходе с одного курсора с одного элемента section на другой происходит остановка прокрутки, (только в firefox)
    на представленном примере эт тоже есть,
    * версии ff перепробовал разные,
    как решить ?

    хе-хе, вот что занчит когда отвлекают,
    исправил:

    столкнулся с такой проблемой как прокруткой в firefox,
    когда курсор переходит с одного элемента section на другой происходит остановка прокрутки, (только в firefox)
    на представленном примере эт тоже есть,
    * версии ff перепробовал разные,
    как решить ?

  23. Михаил 30 января 2009 at 19:52 Permalink

    столкнулся с такой проблемой как прокруткой в firefox,
    когда курсор переходит с одного элемента section на другой происходит остановка прокрутки, (только в firefox)
    на представленном примере эт тоже есть,
    * версии ff перепробовал разные,
    как решить ?

    Тоже с этим столкнулся, тоже хотел бы узнать как это исправить.

  24. Slim 11 февраля 2009 at 20:39 Permalink

    столкнулся с такой проблемой как прокруткой в firefox,
    когда курсор переходит с одного элемента section на другой происходит остановка прокрутки, (только в firefox)
    на представленном примере эт тоже есть,
    * версии ff перепробовал разные,
    как решить ?

    Тоже с этим столкнулся, тоже хотел бы узнать как это исправить.

    Да можно пофиксить эту хрень. Фикситься очень просто. Непонимаю почему автор вставил именно такую реализацию.
    Поменяй сторки

    $(‘container’).addEvent(‘mouseover’, scroll.start.bind(scroll));
    $(‘container’).addEvent(‘mouseout’, scroll.stop.bind(scroll));

    на

    $(‘container’).addEvent(‘mouseenter’, scroll2.start.bind(scroll2));
    $(‘container’).addEvent(‘mouseleave’, scroll2.stop.bind(scroll2));

    И будет тебе щастье :)

  25. Алексайндр 6 апреля 2009 at 4:07 Permalink

    Ссылка битая? Не могу посмотреть пример. Поправите?

  26. Dimon 20 сентября 2009 at 21:47 Permalink

    Очень красиво!

  27. Алексей 10 июня 2010 at 14:22 Permalink

    .slider{
    width: 1200px; height: 120px;
    padding: 5px;
    background: #CECECE;
    }

    width: 1200px – фиксированная ширина, это оооооооооочень плохо, ибо по достижении крайнего слайда – все равно ведет в сторону, пока не будет достигнута заданная ширина. Нужна динамика

  28. Алексей 9 сентября 2010 at 18:56 Permalink

    Подскажите пожалуйста как сделать прокрутку не по области а по нажатию или наведению мышки на кнопку.

  29. Men's Fitness 25 февраля 2012 at 18:32 Permalink

    A number of really nice products on this web site, I quite like this.

  30. Marco Winningham 26 февраля 2012 at 5:24 Permalink

    I simply want to say I am just beginner to blogging and site-building and absolutely enjoyed you’re web blog. More than likely I’m planning to bookmark your site . You definitely come with exceptional article content. Thank you for sharing your blog site.

  31. Watch TV On A PC 28 февраля 2012 at 18:45 Permalink

    Hey there would you mind sharing which blog platform you’re using? I’m going to start my own blog in the near future but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Sorry for being off-topic but I had to ask!

  32. Lourie 29 февраля 2012 at 7:22 Permalink

    Wow! Thank you! I always needed to write on my website something like that. Can I include a fragment of your post to my blog?

  33. Scrapebox forum 29 февраля 2012 at 12:35 Permalink

    Thank you for sharing with us, I conceive this website genuinely stands out : D.

  34. camescope hd 29 февраля 2012 at 17:07 Permalink

    Some genuinely excellent posts on this site, thankyou for contribution.

  35. http://www.veloenfant.org/ 29 февраля 2012 at 18:13 Permalink

    I consider something genuinely special in this website.

  36. disque dur externe ssd 29 февраля 2012 at 19:33 Permalink

    I conceive this site contains very excellent pent content material posts.

  37. chaussure de foot 29 февраля 2012 at 20:50 Permalink

    Thankyou for this howling post, I am glad I discovered this website on yahoo.

  38. vps hosting 29 февраля 2012 at 21:40 Permalink

    Excellent website. A lot of useful info here. I am sending it to some friends ans also sharing in delicious. And certainly, thanks for your effort!

  39. barbecue electrique 29 февраля 2012 at 21:42 Permalink

    We are a bunch of volunteers and starting a new scheme in our community. Your web site offered us with useful info to paintings on. You have done an impressive task and our entire group will likely be thankful to you.

  40. montre gps cardio 29 февраля 2012 at 22:03 Permalink

    Regards for all your efforts that you have put in this. very interesting info . «Nurture your mind with great thoughts.» by Benjamin Disraeli.

  41. 40 yard dumpster independence wi 1 марта 2012 at 0:26 Permalink

    Quite great points you wrote the following..Great stuffI consider youve created some truly helpful factors.Maintain up the great do the job.

  42. ceramic watches 1 марта 2012 at 1:32 Permalink

    Wohh exactly what I was looking for, thankyou for putting up. «Arguments are like fire-arms which a man may keep at home but should not carry about with him.» by Samuel Butler.

  43. chokoloskee charters 1 марта 2012 at 7:02 Permalink

    Right after research several with the weblog posts on the site today, and that i really like your strategy for blogging and site-building. My partner and i bookmarked that to be able to our bookmark website list along with is going to be looking at back quickly. Could you have a look at my web site as well along with tell me everything you assume.

  44. Roberson 1 марта 2012 at 7:34 Permalink

    You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and extremely broad for me. I’m looking forward for your next post, I’ll try to get the hang of it!

  45. web design atlanta 1 марта 2012 at 8:38 Permalink

    Hello There. I found your blog using msn. This is a very well written article. I’ll make sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly comeback.

  46. free proxy 2012 1 марта 2012 at 11:02 Permalink

    Generally I do not read article on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, very nice post.

  47. http://select-restaurant.net/ 1 марта 2012 at 11:48 Permalink

    This is such a great post, and was thinking considerably exactly the same myself. One more wonderful update.

  48. compensation consulting firm 1 марта 2012 at 14:08 Permalink

    Thanks so much for giving everyone a very nice opportunity to read articles and blog posts from this blog. It is usually very cool and also stuffed with fun for me and my office co-workers to search your website particularly 3 times a week to study the new things you will have. And indeed, I am also certainly contented with your spectacular ideas you give. Certain 2 tips in this article are clearly the most effective we have all ever had.

  49. four micro onde 1 марта 2012 at 17:48 Permalink

    This is very attention-grabbing, You’re an overly professional blogger. I’ve joined your rss feed and look forward to in the hunt for more of your excellent post. Also, I’ve shared your site in my social networks!

  50. climatiseur mobile silencieux 1 марта 2012 at 19:09 Permalink

    You are my breathing in, I have few blogs and very sporadically run out from to post : (.


Оставить комментарий