15 апреля 2008 ~ 6575 Комментариев

Делаем простейший спойлер

Простите, но не смог придумать как назвать спойлер на более русский лад, если есть идеи пишите.

Суть спойлера состоит в том что бы разворачивать полный текст из анонса, будет проще если вы увидите это на примере.

Реализация спойлера

Способ реализации прост, jquery скрывает нужный нам блок с текстом, вместо него ставиться ссылка при нажатии на которую текст будет появляться.

Вот заготовка с текстом:

<p>Это основная часть текста<span class="spoiler">, а эта часть скрыта.</span></p>

Подключаем библиотеку «jquery» и настраиваем ее действия:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() { 

    $("span.spoiler").hide();

     $('<a class="reveal">Читать дальше&gt;&gt;</a> ').insertBefore('.spoiler');

    $("a.reveal").click(function(){
        $(this).parents("p").children("span.spoiler").fadeIn(2500);
        $(this).parents("p").children("a.reveal").fadeOut(600);
    });

});
</script>

Готово! Всем приятного вечера ^_^

Посмотреть пример спойлера

Скачать пример спойлера

Первоисточник

6575 Комментариев для “Делаем простейший спойлер”

  1. PuMi 16 апреля 2008 at 1:01 Permalink

    Ой как классно, как раз он мне только что и понадобился.
    Осталось понять как умное php обрезание сделать.

  2. PuMi 16 апреля 2008 at 1:30 Permalink

    Написал, скрипт обрезает 1 предложение. Легко можно изменить на обрезание по новой строки.

    $count_arr) $max_chars2 = $count_arr;
    else $max_chars2 = $max_chars;
    for ($i = 0; $i<$max_chars2; $i++) {
    $comment .= $arr[$i].».»;
    }
    if ($max_chars2 != $count_arr) $comment_content .= «…»;
    print $comment; //Обрезание
    for ($i =$max_chars ; $i

  3. Владимир 16 апреля 2008 at 1:56 Permalink

    $(this).parents(«p»).children(«a.reveal»).fadeOut(600);

    $(this).fadeOut(600); // должно работать.

  4. PuMi 16 апреля 2008 at 3:15 Permalink

    Написал, скрипт обрезает 1 предложение. Легко можно изменить на обрезание по новой строки.
    http://pukas.ru/explode.txt

  5. SciFi 16 апреля 2008 at 14:10 Permalink

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

  6. Я собственной персоной 16 апреля 2008 at 21:55 Permalink

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

    Ну это легко делается по этому же принципу ;-)

  7. Minras 17 апреля 2008 at 2:53 Permalink

    спасибо, забавный пример :)

  8. Бутёк 19 апреля 2008 at 19:56 Permalink

    :-) — вот он, простейший спойлер!

  9. Бутёк 19 апреля 2008 at 19:56 Permalink

    Извиняюсь, [font color="white"]:-)[/font]

  10. assiduus 20 апреля 2008 at 1:43 Permalink

    Ну а что насчет оратного сворачивания спойлера?

  11. Flyer 30 июля 2008 at 6:04 Permalink

    Может кто-то напишет что надо изменить в скрипте чтобы обратно сворачивалось при нажатии на ссылку с class=»reveal»?

  12. Андрей 2 сентября 2008 at 6:41 Permalink

    А как сделать спойлер, который будетподгружать информацию после его раскрытия? Вот страница загружена,спойлерзакрыт, юзер кликает на спойлер и происходит подгрузка того, что внутри.
    Спасибо за помощь.

  13. Viper 26 сентября 2008 at 6:51 Permalink

    Может кто-то напишет что надо изменить в скрипте чтобы обратно сворачивалось при нажатии на ссылку с class=»reveal»?

    Ну а что насчет оратного сворачивания спойлера?

    заместо fadeIn(Out) как у мну сделано

    bla|bla

    $(«.slidedown»).click (function(){$(«#t_video»).slideToggle(«normal»);});

    А как сделать спойлер, который будетподгружать информацию после его раскрытия? Вот страница загружена,спойлерзакрыт, юзер кликает на спойлер и происходит подгрузка того, что внутри.
    Спасибо за помощь.

    примерно вот так $(«#mydiv»).load(«/ajaxtest.php»);

  14. максим 23 мая 2009 at 16:02 Permalink

    у меня не получается поставить спойлер..

  15. Kosmo 20 октября 2009 at 23:25 Permalink

    Может кто-то напишет что надо изменить в скрипте чтобы обратно сворачивалось при нажатии на ссылку с class=”reveal”?

    Ну а что насчет оратного сворачивания спойлера?

    заместо fadeIn(Out) как у мну сделано
    bla|bla
    $(”.slidedown”).click (function(){$(”#t_video”).slideToggle(”normal”);});

    Я не разбираюсь в скриптах, распиши, пожалуйста, поподробнее, что и куда надо вставить, чтобы все заработало. Буду премного благодарен!!

  16. Chi 5 ноября 2009 at 5:30 Permalink

    Действительно будьте добры подробнее как сделать что бы обратно сворачивалось.

  17. Дмитрий 26 ноября 2009 at 1:00 Permalink

    В html.

    function toggleMe(a){
    var e=document.getElementById(a);
    if(!e)return true;
    if(e.style.display==»none»){
    e.style.display=»block»
    } else {
    e.style.display=»none»
    }
    return true;
    }

    Надпись в спойлере!

  18. Kosmo 29 ноября 2009 at 6:58 Permalink

    Ах да, совсем забыл. В конце каждого скрываемого текста необходимо поставить следующую конструкцию:

  19. Kosmo 29 ноября 2009 at 7:10 Permalink

    Сделал кнопку скрытия:

    http://www.mexanik.su/SpoilerRevealerbeta.rar

    Но пока остался 1 минус – некорректно работает при 2х и более спойлеров на странице. Как исправить пока не знаю.
    В чем разница с первоисточником: в теле html документа изменено содержимое тега , в конце каждого стиха добавлены теги (для кнопки «скрыть») и, соответственно, в style.css добавлен стиль на новую кнопку.

  20. Rexedead 8 января 2010 at 1:14 Permalink

    без jquery:

    function blarg(id) {
    var obj = document.getElementById(id);
    if( obj.style.display == «none» ) { obj.style.display = «block»; } else { obj.style.display = «none»; }
    }

    Природа 1
    галерея фоток

    Природа 2
    галерея фоток

  21. Rexedead 8 января 2010 at 1:23 Permalink

    без jquery:
    http://shorttext.com/wmhm8gfrtv

  22. Александер) 3 сентября 2010 at 15:14 Permalink

    [Spoiler]
    ГГ… Спасибо))

  23. Grawl 5 сентября 2010 at 22:29 Permalink

    Вот тут(http://szenprogs.ru/blog/spojler_na_osnove_jquery/2009-10-28-71) спойлер лучше. Закрывается при нажатии на ту же ссылку, от которой и открывается.

  24. max 14 августа 2011 at 20:37 Permalink

    Вот хороший спойлер как на “rutracker.org”
    Работает везде
    Неограниченная вложенность

    webfile.ru/5489455

  25. Sound Cancelling Headphones Comparison 25 февраля 2012 at 20:24 Permalink

    the actual plot line is very boring.

  26. Val Prichard 26 февраля 2012 at 8:43 Permalink

    I just want to say I am just newbie to blogs and honestly liked you’re web page. Very likely I’m planning to bookmark your site . You certainly have amazing articles and reviews. Appreciate it for sharing your web page.

  27. Mens Fitness 26 февраля 2012 at 21:12 Permalink

    Neat publish. Expecting a new sequel …

  28. Susy 29 февраля 2012 at 7:05 Permalink

    Thanks for the instereting articles. I look at clothing/apparel/shoes for color inspiration as well

  29. Dacia 29 февраля 2012 at 7:08 Permalink

    When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

  30. Farley 29 февраля 2012 at 8:20 Permalink

    Aw, this has been a really nice post. In plan I would like to put in writing similar to this additionally * taking time plus actual work to make a very good article… but exactly what do I say… My spouse and i procrastinate a large amount and by virtually no means apparently get something perfo

  31. Fields 29 февраля 2012 at 8:30 Permalink

    There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls feel the impact of just a moment’s pleasure, for the rest of their lives.

  32. Annamaria 29 февраля 2012 at 8:33 Permalink

    Hi, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam responses? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it’s driving me insane so any support is very much appreciated.

  33. MaleExtra 29 февраля 2012 at 12:16 Permalink

    Are searhing for truthful reliable facts about Male Enhancement? The solutions are all in the MaleExtra Answer

  34. Cathrine Amelang 29 февраля 2012 at 14:51 Permalink

    Best slim weight patch,,Best slimweight patch,report of the slim weight patch ,2012 slimweight patch review ,slim weight patchmost recentreview,

  35. Sharlene Liesmann 29 февраля 2012 at 15:13 Permalink

    Top rated slim weight patch,,Most desirable slimweight patch,professional review of the slim weight patch ,2012 slimweight patch review ,slim weight patch newest review,

  36. montregps 29 февраля 2012 at 15:23 Permalink

    I have recently started a blog, the info you offer on this web site has helped me greatly. Thanks for all of your time & work.

  37. Auto approved scrapebox list 29 февраля 2012 at 17:32 Permalink

    Thanks for some other great post. Where else might just anyone get that type of info in such an ideal indicates of writing? I’ve a presentation next week, and I’m at the search for such information.

  38. Lindsay Rassman 29 февраля 2012 at 17:37 Permalink

    I’d must examine with you here. Which is not something I often do! I get pleasure from studying a publish that can make people think. Also, thanks for allowing me to remark!

  39. Flora Snowberger 29 февраля 2012 at 17:57 Permalink

    Thanks for your article. One other thing is individual states have their particular laws that affect people, which makes it quite difficult for the the legislature to come up with a new set of rules concerning property foreclosures on people. The problem is that every state has got own laws which may have impact in a damaging manner in relation to foreclosure plans.

  40. scrapebox tutorial 29 февраля 2012 at 18:36 Permalink

    Your writing is fine and gives food for thought. I hope that I’ll have much more time to read your articles . Regards. I wish you that you often publish new texts and invite you to greet me

  41. auto approved blog 29 февраля 2012 at 19:19 Permalink

    This internet website is my breathing in, extremely excellent pattern and perfect content .

  42. camescope hd 29 февраля 2012 at 21:44 Permalink

    I am impressed with this web site, real I am a big fan.

  43. disquedurssd.net 29 февраля 2012 at 21:51 Permalink

    I just like the valuable information you provide in your articles. I will bookmark your weblog and check once more here regularly. I’m moderately certain I’ll be informed many new stuff right right here! Good luck for the next!

  44. vps hosting 1 марта 2012 at 0:05 Permalink

    Needed to write you one very little observation in order to say thanks once again for those awesome tricks you have discussed here. It’s so particularly generous of you in giving freely all numerous people would’ve sold as an e-book to make some bucks for their own end, and in particular considering that you could have done it in case you considered necessary. These suggestions in addition worked like the easy way to know that someone else have a similar zeal much like mine to see whole lot more with reference to this matter. Certainly there are numerous more fun occasions in the future for individuals who view your website.

  45. how to train a dog 1 марта 2012 at 0:49 Permalink

    Do yoou mind 1ff I qu0te a few of your articles as long as I provide credit and sources back to your weblog? My blog site is in the very same area of interest as yours and my visitors would genuinely benefit from a lot of the information you provide here. Please let me know if this alright with you. Many thanks

  46. rent a dumpster in economy 1 марта 2012 at 1:28 Permalink

    1st Off, allow me to commend your clearness on this topic. I’m not an expert on this issue, but after studying your piece of producing, my comprehending has developed substantially. Please allow me to grab your rss feed to stay in touch with any forthcoming updates.

  47. seo atlanta 1 марта 2012 at 1:48 Permalink

    whoah this weblog is excellent i like studying your posts. Keep up the good work! You realize, a lot of persons are looking around for this information, you can aid them greatly.

  48. Miles 1 марта 2012 at 2:05 Permalink

    I was very pleased to find this web-site.I wanted to thanks for your time for this wonderful read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you blog post.

  49. Strong 1 марта 2012 at 2:16 Permalink

    whoah this blog is great i love reading your posts. Keep up the great work! You know, lots of people are searching around for this info, you could help them greatly.

  50. Kai 1 марта 2012 at 2:19 Permalink

    Wow I really like those. If I passed those in a department store I would probably stop and look at them


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