0

Есть страница

введите сюда описание изображения

и код

body {
    margin: 0;
    padding: 0;
}

.globalcontainer {
    margin-top: 0px;
    margin-right: 4%;
    margin-bottom: 0px;
    margin-left: 4%;
    height: 100%;
}

.header > .header__text {
position: relative;
width: 93px;
height: 24px;
left: 0;
margin-top: 129px;
margin-bottom: 20px;

font-family: TT Norms;
font-style: normal;
font-weight: bold;
font-size: 24px;
line-height: 100%;
/* identical to box height, or 24px */


color: #000000;
}

/*
.header__buttons {
    left: 0;
    top: 193px;
}
*/


.header__button {
    width: 75px;
    height: 30px;
    border-radius: 4px;
    border-color: #5f3ec0;
    background-color: #fff;
    margin-right: 1.75%;
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
}

.header__buttons {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 7px 15px 7px 0px;
    /*margin-right: 10%;*/
}

.content {
    width: 100%;
}

.cardexample {
    width: 100%;
}

.mobileimage img{
    max-width: 100%;
    height: auto;
}

.mobiles {
    max-width: 100%;
}

.content__title {
    font-family: TTNorms-Medium;
    font-style: normal;
    font-weight: bold;
    font-size: 18px;
    line-height: 21.6px;
    
    margin: 0.3% 15px 0 15px;
}

.crashvideo {
    width: 115px;
    height: 30px;
    border-radius: 4px;
    margin-top: 15px;
    
    background-color: #5f3ec0;
    color: #ffffff;
}

.video__icon {
    margin-left: 15px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
}

#ex2 {
    display: none;
}

.youtube__icon-play {
    margin-left: 30.5px;
    margin-top: 20.5px;
    
    align: center;
}

.content__text {
    margin-top: 16px;
    text-align: left;
    margin-left: 15px;
    margin-right: 90px;
    
    font-family: TT Norms;
    font-style: normal;
    font-weight: normal;
    font-size: 16px;
    line-height: 150%;
    /* or 22px */


    /* Main text */

    color: #cacaca;
}

.endlink {
    margin-top: 20px;
    margin-left: 15px;
    
    font-family: TT Norms;
    font-style: normal;
    font-weight: bold;
    font-size: 16px;
    line-height: 100%;
    color: #121212;
}
<html>
<head>
<!-- <link rel="stylesheet" href="testsite.css">-->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Example</title>
<link rel="stylesheet" type="text/css" href="../css/mobile.css" media="screen and (min-width: 320px) and (max-width: 639px)"></link>
<link rel="stylesheet" type="text/css" href="../css/tablet.css" media="screen and (min-width: 640px) and (max-width: 1023px)"></link>
<link rel="stylesheet" type="text/css" href="../css/desktop.css" media="screen and (min-width: 1024px) and (max-width: 1920px)"></link>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<body>
    <div class="globalcontainer">
        <div class="header">
                <div class="header__text">
                    Обзоры
                </div>
                <div class="header__buttons">
                    <!-- <span> -->
                        <button class="header__button">Все</button>
                        <button class="header__button">Видео</button>               
                        <button class="header__button">Текст</button>               
                        <button class="header__button">Обзоры</button>
                        <button class="header__button">Сравнения</button>
                        <button class="header__button">Краш видео</button>
                        <button class="header__button">Распаковка</button>
                    <!-- </span> -->
                </div>
        </div>      
        <div class="content">       
                <div class="cardexample">
                    <div class="mobileimage">
                        <img class="mobiles" src="../img/mobileimage.png">
                    </div>
                    <div class="content__title">
                        Iphone 11, почему такой же как и Pro Max, может быть большим в 3 строки вот так
                    </div>
                        <div class="video__icon">
                            <span>
                                <button class="crashvideo">Краш видео</button>
                            </span>
                            <span>
                                <a href="#"><img class="youtube__icon-play" src="../img/Vector.png"></a>
                            </span> 
                            <span>
                                <button class="crashvideo" id="ex2">Краш видео</button>
                            </span>                         
                        </div>
                    <div class="content__text">
                        Видео разбор с ответами на самые часто задаваемые вопросы может быть большим в 3 строки, видео разбор с ответами на самые часто задаваемые
                    </div>
                    <div class="endlink">
                        <a href="#">Читать далее</a>
                    </div>
                </div>
                <div class="cardexample">
                        <div class="mobileimage">
                                <img class="mobiles" src="../img/mobileimage.png">
                        </div>
                        <div class="content__title">
                            Iphone 11, почему такой же как и Pro Max, может быть большим в 3 строки вот так
                        </div>
                        <div class="video__icon">
                            <span>
                                <button class="crashvideo">Краш видео</button>
                            </span>
                            <span>
                                <a href="#"><img class="youtube__icon-play" src="../img/Vector.png"></a>
                            </span> 
                            <span>
                                <button class="crashvideo" id="ex2">Краш видео</button>
                            </span>                         
                        </div>
                        <div class="content__text">
                            Видео разбор с ответами на самые часто задаваемые вопросы может быть большим в 3 строки, видео разбор с ответами на самые часто задаваемые
                        </div>
                        <div class="endlink">
                            <a href="#">Читать далее</a>
                        </div>              
                </div>
                <div class="cardexample">
                </div>
                <div class="cardexample">
                </div>
        </div>      
    </div>
<script type="text/javascript" src="jsactions.js"></script>
</body>
</html>

Как избавиться от дублирования кода

                <div class="cardexample">
                        <div class="mobileimage">
                                <img class="mobiles" src="../img/mobileimage.png">
                        </div>
                        <div class="content__title">
                            Iphone 11, почему такой же как и Pro Max, может быть большим в 3 строки вот так
                        </div>
                        <div class="video__icon">
                            <span>
                                <button class="crashvideo">Краш видео</button>
                            </span>
                            <span>
                                <a href="#"><img class="youtube__icon-play" src="../img/Vector.png"></a>
                            </span> 
                            <span>
                                <button class="crashvideo" id="ex2">Краш видео</button>
                            </span>                         
                        </div>
                        <div class="content__text">
                            Видео разбор с ответами на самые часто задаваемые вопросы может быть большим в 3 строки, видео разбор с ответами на самые часто задаваемые
                        </div>
                        <div class="endlink">
                            <a href="#">Читать далее</a>
                        </div>              
                </div>

6
  • А этот код генерируется серверной стороной? Или просто как статичный html? Таких блоков будет много или нет? 23 апр 2021 в 14:25
  • @АлексейШиманский: на самом деле, здесь "XY problem" уже полгода ;-)
    – UModeL
    23 апр 2021 в 14:45
  • @АлексейШиманский этот код - просто статический html. Таких блоков 8.
    – itspec891
    23 апр 2021 в 14:55
  • 1
    @UModeL интригующе. 23 апр 2021 в 15:02
  • 1
    @itspec891 Вы принципиально не отмечаете "галочкой" ответа на Ваши вопросы?
    – user176262
    23 апр 2021 в 16:32

1 ответ 1

2

Приведу лишь пример. Я думаю по образу и подобию вы сделаете.

Заводим массив объектов с основными данными (например картинка, заголовок и текст), создаем метод, который отдаёт шаблонную строку с HTML, которая как раз дублируется по сто раз на странице и далее пробегаемся циклом по изначальному массиву вызывая метод с шаблоном и формируя контент. Далее этот контент вставляем в нужный элемент.

// Массив объектов с данными, которые нужно применять в каждом повторяющемся блоке
let data = [
    { img: 'https://i.pinimg.com/564x/a9/3c/b4/a93cb4e0316ef9c4db83846550ff4deb.jpg', title: 'Заголовок 1', text: 'Полный текст 1' },
    { img: 'https://vjoy.cc/wp-content/uploads/2019/05/1-13.jpg', title: 'Заголовок 2', text: 'Полный текст 2' },
    { img: 'https://klike.net/uploads/posts/2018-06/1528641366_2.jpg', title: 'Заголовок 3', text: 'Полный текст 3' },
    { img: 'https://i.pinimg.com/originals/37/26/27/3726273afdaf29d8eb0312a34b85874b.jpg', title: 'Заголовок 4', text: 'Полный текст 4' },
];

// Функция, которая возвращает один элемент повторяющегося шаблона
// с вставкой в него переменных
const getRowTemplate = (img, title, text) => {
    return `
        <div class="row">
            <img src="${img}" />
            <p>Заголовок новости таков: ${title}</p>
            <p>А вот основной текст новости:</p>
            <div>${text}</div>
        </div>
    `;
};

// Функция, которая пробегается по всему массиву и на каждой итерации
// подставляет данные из одного элемента массива в функиwb. взятия шаблона Html
const getAllNews = (data) => {
    let content = '';
    
    data.forEach(el => {
        content += getRowTemplate(el.img, el.title, el.text);
    });
    
    return content;
};

// Функция рендера всего контента на основе переданных данных
const renderAllNews = (data) => {
    document.getElementById('news').innerHTML = getAllNews(data);
};

renderAllNews(data);
.row {
    border: 1px solid black;
    padding: 5px;
    margin: 5px;
}

img {
  width: 70px;
  
}
<div id="news"><div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.