Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Как изменить количество фотографий на странице без перехода на другую страницу? (https://javascript.ru/forum/dom-window/81413-kak-izmenit-kolichestvo-fotografijj-na-stranice-bez-perekhoda-na-druguyu-stranicu.html)

Sergey-web92 21.11.2020 19:44

Как изменить количество фотографий на странице без перехода на другую страницу?
 
Здравствуйте! Помогите пожалуйста разобраться.
Делаю для сайта пагинацию. У меня по умолчанию на всех страницах отображается по три фотки. Мне нужно, чтобы при нажатии на верхние кнопки- количество фоток менялось на странице мгновенно(кнопка "2-count"-показывает по две фотки на странице, кнопка "3-count"-показывает по три фотки).
У меня меняется количество фоток при нажатии кнопок "2-count" или "3-count", но только при дальнейшем переходе на следующую страницу(при нажатии на нижние кнопки).

П.С. сначала я нажимаю на любую нижнюю кнопку(отвечающую за номер страницы) => отображаются фотки на странице. кнопки вверху отвечают за количество фоток, отображаемых на выбранной странице.

<!DOCTYPE html>
<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
<style type="text/css">
#table td {
  padding: 10px;
  border: 1px solid black;
}

#pagination {
  display: flex;
  padding: 0;
  list-style-type: none;
}
#pagination li {
  margin-right: 5px;
  padding: 10px;
  border: 1px solid black;
}
#pagination li:hover,
#pagination li.active {
  cursor: pointer;
  color: red;
  border: 1px solid red;
}

.flex-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

#table {
  width: 90%;
  height: 100%;
  display: flex;
  justify-content: center;
}

.testi {
  width: 33.33333%;
  height: 100px;
  margin: 10px;
  border: 1px solid blue;
}

// test content

.main-content {
  width: 100%;
  height: 100%;
  border: 1px solid blue;
  display: flex;
  justify-content: center;
}
.test-table {
  width: 90%;
  height: 250px;
  border: 1px solid red;
  display: flex;
}
.test-img {
  width: 33.333333%;
  height: 100%;
  border: 1px solid green;
  background-image: url("https://picsum.photos/200/300?random=2");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  padding: 20px;
}

// ===
.picture_1 {
  background-image: url("https://picsum.photos/200/300?random=1");
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.picture_2 {
  background-image: url("https://picsum.photos/200/300?random=2");
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.picture_3 {
  background-image: url("https://picsum.photos/200/300?random=3");
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.picture_4 {
  background-image: url("https://picsum.photos/200/300?random=4");
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

.picture_5 {
  background-image: url("https://picsum.photos/200/300?random=5");
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.picture_6 {
  background-image: url("https://picsum.photos/200/300?random=6");
  width: 100%;
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

</style>
</head>

<body>
<main class="page-main">
        <div class="button-container">
            <button class="twobtn">2-count</button>
            <button class="threebtn">3-count</button>
        </div>
        <div class="flex-wrap">
        <div id="table">
            
        </div>
        </div>
        <ul id="pagination">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    </main>
<script>
let users = [
	{name: 'picture_1'},
	{name: 'picture_2'},
	{name: 'picture_3'},
	{name: 'picture_4'},
	{name: 'picture_5'},
	{name: 'picture_6'},
];
let table = document.querySelector('#table');
let items = document.querySelectorAll('#pagination li');

let notesOnPage = 3;

for (let item of items) {
  item.addEventListener('click', function () {
    let pageNum = +this.innerHTML;
    
    let start = (pageNum - 1) * notesOnPage;
    let end = start + notesOnPage;

    let notes = users.slice(start, end);
   
    table.innerHTML = '';

    for (let note of notes) {
      let tr = document.createElement('div');
      tr.classList.add('testi');
      table.appendChild(tr);

      let td;

      td = document.createElement('div');
      td.classList.add(note.name);
      tr.appendChild(td);
    }
  })
}

// test button pagination


const togglet = document.querySelector(".twobtn")
const togglett = document.querySelector(".threebtn")


togglet.addEventListener("click", function(){
  notesOnPage = 2;
});
togglett.addEventListener("click", function(){
  notesOnPage = 3;
});
</script>
</body>
</html>

рони 21.11.2020 20:37

Sergey-web92,
что делают кнопки 1, 2, 3?

Sergey-web92 21.11.2020 21:02

Цитата:

Сообщение от рони (Сообщение 531027)
Sergey-web92,
что делают кнопки 1, 2, 3?

эти кнопки отвечают за страницы. при нажатии на кнопку 2 - откроется вторая страница, при нажатии на кнопку 3 - откроется третья страница.

рони 21.11.2020 22:02

постраничный вывод фотографий
 
Sergey-web92,

<!DOCTYPE html>
<html>
<head>
    <title>Untitled</title>
    <meta charset="utf-8">
<style type="text/css">
#pagination {
    display: flex;
    padding: 0;
    list-style-type: none;
    justify-content: center;
}
#pagination li {
    margin-right: 5px;
    padding: 10px;
    border: 1px solid black;
}
#pagination li:hover,
#pagination li.active {
    cursor: pointer;
    color: red;
    border: 1px solid red;
}
.flex-wrap {
    width: 100%;
    height: 250px;
    display: flex;
    justify-content: center;
}
.flex-wrap div{
    width: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    background-image: var(--img);
    margin: 10px;
    border: 1px solid black;
    box-sizing: border-box;
}
.page-main {
    width: 90%;
    margin: 0 auto;
}
.button-container .btn:after{
    content: attr(data-count)
}
.button-container{
   display: flex;
   justify-content: center;
}
.button-container .btn{
   margin-right: 15px;
}
.button-container .btn.active{
     background-color: #FFFAFA;
     outline: none;
     font-weight: bold;
}
</style>
</head>
<body>
<main class="page-main">
                <div class="button-container">
                </div>
                <div class="flex-wrap">
                </div>
                <ul id="pagination">
                </ul>
        </main>
<script>
let users = [
    {name: 'https://picsum.photos/200/300?random=1'},
    {name: 'https://picsum.photos/200/300?random=2'},
    {name: 'https://picsum.photos/200/300?random=3'},
    {name: 'https://picsum.photos/200/300?random=4'},
    {name: 'https://picsum.photos/200/300?random=5'},
    {name: 'https://picsum.photos/200/300?random=6'}
];
let table = document.querySelector('.flex-wrap');
let pagination = document.querySelector('#pagination');
let index = 0;
let len = users.length;
let notesOnPage = 3;
const show = i => {
    table.innerHTML = '';
    for (let max = i + notesOnPage; i < max; i++) {
        let td = document.createElement('div');
        td.style.setProperty('--img', `url("${users[i].name}")`);
        table.append(td);
    }
}
show(index)
const page = () => {
    pagination.innerHTML = '';
    for (let i = 0; i < len; i += notesOnPage) {
        let li = document.createElement('li');
        li.textContent = (i / notesOnPage) + 1;
        let indexPage = Math.min(i, len - notesOnPage);
        li.dataset.index = indexPage;
        if (index >= indexPage && index < indexPage + notesOnPage) {
            li.classList.add('active');
            index = indexPage;
            show(index);
        }
        pagination.append(li);
    }
}
page();
pagination.addEventListener('click', ({target}) => {
    let i = target.dataset.index;
    if (i === void 0) return;
    pagination.querySelectorAll('li').forEach(li => li.classList.toggle('active', li === target));
    index = +i;
    show(index)
})

const buttonContainer = document.querySelector(".button-container");
const counts = [1, 2, 3, 5, 6];
const btnCount = ar => ar.forEach(num => {
    let btn = document.createElement('button');
    btn.classList.add('btn');
    if(num == notesOnPage) btn.classList.add('active');
    btn.dataset.count = Math.min(len, num);
    buttonContainer.append(btn);
})
btnCount(counts)

buttonContainer.addEventListener("click", ({target}) => {
    let count = target.dataset.count;
    if (count === void 0) return;
    buttonContainer.querySelectorAll('.btn').forEach(btn => btn.classList.toggle('active', btn === target));
    notesOnPage = +count;
    page();
});

</script>
</body>
</html>

Sergey-web92 21.11.2020 23:04

рони, большое спасибо за Вашу помощь)

рони 22.11.2020 00:46

Sergey-web92,
код выше был изменён, количество фоток на страницу, можно задать, массивом значений, строка 118.

Sergey-web92 22.11.2020 17:22

Цитата:

Сообщение от рони (Сообщение 531033)
Sergey-web92,
код выше был изменён, количество фоток на страницу, можно задать, массивом значений, строка 118.

понял, спасибо!


Часовой пояс GMT +3, время: 14:56.