Объявление
Уважаемые читатели, друзья, подписчики. В связи с участившимся и, порядком надоевшим спамом в комментариях от всяких анонимах(будь они не ладны), я вынуждена включить модерацию комментариев на некоторое время. Очень надеюсь на ваше понимание.

переключатель отображения постов списком/сеткой BLOGGER

Доброго времени суток, друзья. По умолчанию сообщения на главной странице блога отображены в виде списка. Но наверняка, вы обращали внимание, что на некоторых современных сайтах  посты на главной показаны в виде сетки. Что очень привлекает к себе внимание. 

Хочу с вами поделиться вариантом как сделать в Блоггере переключатель постов между сеткой и списком. Чтобы пользователь сам мог решить, как ему удобнее воспринимать информацию. 

Вот так привычно будет выглядеть расположение постов списком

отображение постов на главной


А вот так в виде сетки

отображение постов на главной странице


Такие кнопки будут видны только на главной странице, странице ярлыков и архива.
  • Лёгким нажатием на кнопку читатель может перейти в нужный режим просмотра. 
  • В коде не предусмотрен скрипт библиотеки jQuery.
  • В режиме списка сообщения будут отображаться с автоматической кнопкой читать дальше и миниатюрами, заданного размера.
  • В режиме сетки при наведении используем красивый hover-эффект с лёгкой прозрачностью, отображается название поста с количеством комментариев. 
Посмотрите, как это выглядит на тестовом блоге


Если появилось желание установить у сея такой переключатель отображения список/сетка, давайте перейдём к установке.

Все изменения и дополнения нужно делать непосредственно во вкладке Тема. Поэтому заранее рекомендую сделать резервную копию шаблона или потренироваться на тестовом блоге. Хотя особо сложного ничего нет.

Идём во вкладку Тема и находим закрывающийся тег </head>. Над ним устанавливаем следующий код

<script type='text/javascript'>
function list_view(){
if(document.getElementsByClassName(&quot;post&quot;)) {elementArray = document.getElementsByClassName(&quot;post&quot;); while (elementArray.length) {elementArray[0].className = &quot;post-grid-view&quot;;}}
if(document.getElementsByClassName(&quot;post-title&quot;)) {elementArray = document.getElementsByClassName(&quot;post-title&quot;); while (elementArray.length) {elementArray[0].className = &quot;post-title-grid&quot;;}}
}
function grid_view(){
if(document.getElementsByClassName(&quot;post-grid-view&quot;)) {elementArray = document.getElementsByClassName(&quot;post-grid-view&quot;); while (elementArray.length) {elementArray[0].className = &quot;post&quot;;}}
if(document.getElementsByClassName(&quot;post-title-grid&quot;)) {elementArray = document.getElementsByClassName(&quot;post-title-grid&quot;); while (elementArray.length) {elementArray[0].className = &quot;post-title&quot;;}}
}
</script>
 <script type='text/javascript'>
posts_no_thumb_sum = 100;
posts_thumb_sum = 350;
</script>

<script type='text/javascript'>
//<![CDATA[
function removeHtmlTag(strx,chop){
if(strx.indexOf("<")!=-1)
{
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length-1) ? chop : strx.length-2;
while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++;
strx = strx.substring(0,chop-1);
return strx+'...';
}
function createSummaryAndThumb(pID, pURL, pTITLE){
var div = document.getElementById(pID);
var imgtag = "";
var img = div.getElementsByTagName("img");
var summ = posts_no_thumb_sum;
if(img.length>=1) {
imgtag = '<span class="posts-thumb" style="float:left; margin-right: 10px;"><a href="'+ pURL +'"><img src="'+img[0].src+'" /></a></span>';
summ = posts_thumb_sum;
}

else {
imgtag = '<span class="posts-thumb" style="float:left; margin-right: 10px;"><a href="'+ pURL +'" title="'+ pTITLE+'"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsZqTV-ShBWpV4bzed55gW0Czs6UwRyPG4JffUyF0ha8QUllhSlcL9MSD8FUHO726Qo9QRNUDrp3xMEspXN3MnjEIK-MBg_GPA0goOmBi4-Eya_qQ5EESByHIY-uNgxgIBbdnk-HMJFtzK/s1600/sorry-image-not-available.png" style="margin-top: -30px;" /></a></span>';
summ = posts_thumb_sum;
}

var summary = imgtag + '<a href="'+ pURL +'"><div class="post-summary-text">' + removeHtmlTag(div.innerHTML,summ) + '</div></a>';
div.innerHTML = summary;
}
//]]>
</script>

<b:if cond='data:blog.pageType != &quot;static_page&quot;'>
<b:if cond='data:blog.pageType!= &quot;item&quot;'>
<style>
#list-view-button {font-family: Verdana; text-align:left;cursor:pointer;font-size: 14px;border-bottom: 5px solid #eaeaea;text-decoration: none;}
#list-view-button a{text-decoration: none; color: #666;}
.grid-view-button {background-color:#efefef;color:#666;padding:5px 10px;border-radius: 5px;font-size: 12px;}
.list-view-button {background-color:#efefef;color:#000;padding:5px 10px;border-radius: 5px;font-size: 12px;}
.post-grid-view {width:100%;height:250px;overflow: hidden;float:left;margin:0px 0px 20px !important;position:relative;display: block; -webkit-transition:all 0.5s ease 0s; -moz-transition:all 0.5s ease 0s; -o-transition:all 0.5s ease 0s; transition:all 0.5s ease 0s; }
.post-grid-view .posts-thumb {width:40% !important;height:250px !important;float:left;margin:0px;position:relative;border-top: 0px solid transparent !important;overflow: hidden;}
.post-grid-view .post-header {display: none;}
.post-grid-view .post-body img {min-width: 300px !important; min-height: 250px !important;display:block;width:100%!important;height:auto!important;max-width:800px!important;max-height:400px!important;border:none;outline:none;position:relative;margin: 0px;padding:0;}
.post-grid-view .post-summary-text {opacity: 1; background: none; width: 58%;font-size: 120% !important;clear: none !important; display: inline-block !important; padding: 80px 0px !important; color: #666 !important; text-shadow: none !important; float: right !important; text-align: left; position: relative !important; font-family: &#39;Open Sans Condensed&#39;, sans-serif;}
.post-grid-view .post-body {height: 250px;background:#f5f5f5; box-shadow: none !important;}
.post-title-grid a { font-size:170%;color: #777;font-family: &#39;Open Sans Condensed&#39;, sans-serif;}
.post-title-grid { position: absolute; left: 42%; top: 5%; z-index: 1;}
.post-grid-view .post-footer {left: 41%; display:block;position: absolute; bottom: 2%;font-size: 120%; background: transparent !important; border: 0px solid transparent !important;font-family: &#39;Open Sans Condensed&#39;, sans-serif;}
.post-grid-view .post-footer a{color: #128EC9;}
.post-grid-view a.comment-bubble {display: none;}
.main-inner .column-center-inner .section {margin: 0px !important;}
.post { -webkit-transition:all 0.5s ease 0s; -moz-transition:all 0.5s ease 0s; -o-transition:all 0.5s ease 0s; transition:all 0.5s ease 0s;}

#blog-pager {clear:both;}
.post {height:auto;width:32.2%;display:inline-block;text-decoration:none;float:left;margin:0 1% 1% 0%;overflow: hidden;padding:0!important;}
.date-header {display: none;}
h3.post-title a {font-size:90%;font-family: &#39;Open Sans Condensed&#39;, sans-serif;text-transform:uppercase;color:#fff;text-shadow: 1px 1px 0 rgba(0, 0, 0, 0.1);font-weight: bold;}
h3.post-title {text-align: center; position:absolute;top:0;width:100%;overflow:hidden;margin:0px !important;padding-top: 30%; background-color: rgba(50, 126, 213, 0.8);transform: scale(1);opacity: 0;z-index: 10;height: 100%;transition: all 300ms ease-out 0s;}
h3.post-title:hover {opacity: 1;}
.posts-thumb {width:100%!important;height:200px!important;overflow:hidden;clear:both;}
.post-body {border-radius:2px;box-shadow:0 5px 4px 1px rgba(0,0,0,0.1);position:relative;overflow: hidden;}
.post-body a {text-decoration: none;}
.post-body img {display:block;width:100%!important;height:auto!important;max-width:800px!important;max-height:400px!important;min-width:200px!important;min-height:200px!important;border:none;outline:none;position:relative;margin: 0px;padding:0;}
.post-summary-text {display: none;}
a.comment-bubble {color:#fff;text-decoration:none;font-size:100%;width: 100%;text-align: center;position:absolute;top:175px;left: 0px;text-shadow:1px 2px 1px #333;font-family: &#39;Pacifico&#39;, cursive;z-index: 122;}
a.comment-bubble:before { content: &quot;Комментариев: &quot; url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKzUFqYLwUy8zxL0afEiNEJ4mO3xFhdXuwlV3koE82BU6fi8lfmTVvQ3SepjyCgK5C9xDBUUbJzVMzkhYQhS9pLc9EMYor0oU3Pr_HeyhZ3QgNpyu1_qUHqrQ__up_3h-mtkjW-BWTKN39/s1600/heart-active.png);}
.post-header,.post-footer {display:none;}
</style></b:if></b:if>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'/>

background-color:#efefef; цвет кнопок
Зелёным - иконка сердечка в стилях сетки

Затем нужно найти строку

<b:section class='main' id='main' name='Main' showaddelement='no'>


или

<b:section class='main' id='main' name='Main' showaddelement='yes'>

Над ней вставить следующий код 

<b:if cond='data:blog.pageType != &quot;static_page&quot;'>
<b:if cond='data:blog.pageType!= &quot;item&quot;'>
<div id='list-view-button'><a class='grid-view-button' onclick='grid_view()'><img src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEij6YNClJoTf09cWlHjdeGxjTx9eBTW2cCB8fCroH3qpl5X5zh0pyn5BpgHPzircND1bvKzcXXfQCSVkiBKR-KBdXWeunhzQ0cc3owPS0k158KWlzQYtdF45H-38AzxNgftSYRtj5sQFpQk/s1600/search-grid-icon.png' style='margin: -8px 1px -3px -6px;width: 16px;'/> Отобразить сеткой</a> <a class='list-view-button' onclick='list_view()'><img src='https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_7x_eJTDmKtN8jrOLazHwLOSfb8ZZvmMHk5v7-i9OstzMdNUf2JVRYx2fc9m6M2eJhpw2IPdXg1BxSb-cKrsrIGmi_Z6TW4-s0vuoNPP0Gr_lZDUb7u9IPA_aL9o-Qxo_E7KQhiQm_dXj/s1600/icon-list-view.png' style='margin: -8px 1px -3px -6px;width: 16px;'/> Отобразить списком</a></div>
</b:if></b:if>

Зелёным цветом отмечены иконки переключателя

Сейчас находим строку

<data:post.body/>

Обычно таких строк несколько. В моём случае на одном из тестовых блогов было 2 на другом 3. Замените вторую, если два вхождения или вторую и третью, если таковых у вас три, на следующий код

<b:if cond='data:blog.pageType != &quot;static_page&quot;'>     <b:if cond='data:blog.pageType != &quot;item&quot;'>         <div expr:id='&quot;summary&quot; + data:post.id'>             <data:post.body/>         </div>         <script type='text/javascript'>createSummaryAndThumb(&quot;summary<data:post.id/>&quot;,&quot;<data:post.url/>&quot;);</script>         <b:if cond='data:post.allowComments'>             <a class='comment-bubble' expr:href='data:post.addCommentUrl' expr:onclick='data:post.addCommentOnclick'>                 <data:post.numComments/>             </a>         </b:if>     </b:if> </b:if> <b:if cond='data:blog.pageType == &quot;item&quot;'>     <data:post.body/> </b:if> <b:if cond='data:blog.pageType == &quot;static_page&quot;'>     <data:post.body/> </b:if>

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

Подглядела решение здесь. Но пришлось много в коде перекроить для корректного отображения. Если возникнут вопросы, обращайтесь в комментариях.

Желаю вам удачи.
  
здесь можно оформить подписку на новости блога

Введите Ваш email


3 комментария:

  1. Я не поняла, что значит сеткой, хотя и посмотрела экспериментальный блог.

    ОтветитьУдалить
  2. Спасибо за интересную информацию )))

    ОтветитьУдалить
  3. Ирина, то статьи идут полосой вниз, а то скомпанованы как на картинке второй (это и называется сеткой). Как не увидеть разницу.

    ОтветитьУдалить

ВСЕГДА РАДА УСЛЫШАТЬ ВАШЕ МНЕНИЕ!
Ели у вас возникла необходимость опубликовать код в комментарии, то воспользуйтесь encoder HTML