Укоротить код js - выбор цвета

Рейтинг: 0Ответов: 2Опубликовано: 16.07.2023

Есть input поля с цветами для настройки внешнего вида (цветовой схемы) таблицы.

window.oninput = function oninputColor() {
  let idColor_th = document.getElementById("idColor_th").value;
  document.getElementsByClassName("th")[1].style.backgroundColor = idColor_th;
  document.getElementsByClassName("th")[2].style.backgroundColor = idColor_th;
  document.getElementsByClassName("th")[3].style.backgroundColor = idColor_th;

  let idColor_th_text = document.getElementById("idColor_th_text").value;
  document.getElementsByClassName("th")[1].style.color = idColor_th_text;
  document.getElementsByClassName("th")[2].style.color = idColor_th_text;
  document.getElementsByClassName("th")[3].style.color = idColor_th_text;

  let idColor_td1 = document.getElementById("idColor_td1").value;
  document.getElementsByClassName("td1")[0].style.backgroundColor = idColor_td1;
  document.getElementsByClassName("td1")[1].style.backgroundColor = idColor_td1;

  let idColor_td1_text = document.getElementById("idColor_td1_text").value;
  document.getElementsByClassName("td1")[0].style.color = idColor_td1_text;
  document.getElementsByClassName("td1")[1].style.color = idColor_td1_text;

  let idColor_td2 = document.getElementById("idColor_td2").value;
  document.getElementsByClassName("td2")[0].style.backgroundColor = idColor_td2;
  document.getElementsByClassName("td2")[1].style.backgroundColor = idColor_td2;

  let idColor_td2_text = document.getElementById("idColor_td2_text").value;
  document.getElementsByClassName("td2")[0].style.color = idColor_td2_text;
  document.getElementsByClassName("td2")[1].style.color = idColor_td2_text;
}
.tlist{
    table-layout: fixed;
}
.tlist th{
    background: #efefef;
    border: 1px solid #cfcfcf;
}
.tlist td{
    border: 1px solid #eee;
}
.tlist tbody tr:nth-child(odd){
    background: #fff;
}
.tlist tbody tr:nth-child(even){
    background: #f7f7f7;
}
<form action="" method="post">
    <table>
        <tr>
            <td>Шапка</td>
            <td class="w250">
                <input type="color" id="idColor_th" name="color_th" value="#efefef"></td>
            <td rowspan="8" style="vertical-align:top;">

                <table id="pattern" class="tlist">
                    <tr class="th">
                        <th class="th">Столбец 1</th>
                        <th class="th">Столбец 2</th>
                        <th class="th">Столбец 3</th>
                    </tr>
                    <tr class="td1">
                        <td>Цифры</td>
                        <td>123 456,78</td>
                        <td>90 987 123,00</td>
                    </tr>
                    <tr class="td2">
                        <td>Дата</td>
                        <td>05.01.2023</td>
                        <td>14.07.2023</td>
                    </tr>
                    <tr class="td1">
                        <td>Контакты</td>
                        <td>example@pochta.uz</td>
                        <td>+998 00 123 45 78</td>
                    </tr>
                    <tr class="td2">
                        <td>Данные</td>
                        <td>Маткарим Маримбоевич</td>
                        <td>ООО "NAME"</td>
                    </tr>
                </table>

            </td>
        </tr>
        <tr>
            <td>Текст шапки</td>
            <td><input type="color" id="idColor_th_text" name="color_th_text" value="#000000"></td>
        </tr>
        <tr>
            <td>Нечётные строки</td>
            <td><input type="color" id="idColor_td1" name="color_td1" value="#f7f7f7"></td>
        </tr>
        <tr>
            <td>Текст нечётных строк</td>
            <td><input type="color" id="idColor_td1_text" name="color_td1_text" value="#000000"></td>
        </tr>
        <tr>
            <td>Чётные строки</td>
            <td><input type="color" id="idColor_td2" name="color_td2" value="#ffffff"></td>
        </tr>
        <tr>
            <td>Текст чётных строк</td>
            <td><input type="color" id="idColor_td2_text" name="color_td2_text" value="#000000"></td>
        </tr>
        <tr>
            <td>Название стиля</td>
            <td><input type="text" name="theme_name"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Сохранить" name="save_theme_btn"></td>
            <td></td>
        </tr>
    </table>
</form>

Код JS громоздкий. Уверен что есть короткий и элегантный аналог этого кода. Как лучше написать? Заранее спасибо)

Ответы

▲ 1

Вот один из вариантов.

window.oninput = function oninputColor() {
    let tcells, idColor_td, idColor_td_text;
    let theads = document.getElementsByClassName("th");
    let idColor_th = document.getElementById("idColor_th").value;
    let idColor_th_text = document.getElementById("idColor_th_text").value;
    for (i = 0; i < theads.length; i++) {
        theads[i].style.backgroundColor = idColor_th;
        theads[i].style.color = idColor_th_text;
    }

    for (i = 1; i <= 2; i++) {
        tcells = document.getElementsByClassName('td'+i);
        idColor_td = document.getElementById('idColor_td'+i).value;
        idColor_td_text = document.getElementById('idColor_td'+i+'_text').value;
        for (j = 0; j < tcells.length; j++) {
            tcells[j].style.backgroundColor = idColor_td;
            tcells[j].style.color = idColor_td_text;
        }
    }
}
▲ 1

Укоротить код js - выбор цвета

Поскольку теги ТСа предполагают использование jQuery - предложу такой вариант "укорачивания" кода.

const def = [
  {v: '#idColor_th', t: '.th'},
  {v: '#idColor_td1', t: '.td1'},
  {v: '#idColor_td2', t: '.td2'},
]
$(document).on('input', function oninputColor() {
  def.forEach(o => {
    const e = $(o.t)
    e.css('backgroundColor', $(o.v).val())
    e.css('color', $(o.v + '_text').val())
  })
})
.tlist{
    table-layout: fixed;
}
.tlist th{
    background: #efefef;
    border: 1px solid #cfcfcf;
}
.tlist td{
    border: 1px solid #eee;
}
.tlist tbody tr:nth-child(odd){
    background: #fff;
}
.tlist tbody tr:nth-child(even){
    background: #f7f7f7;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
    <table>
        <tr>
            <td>Шапка</td>
            <td class="w250">
                <input type="color" id="idColor_th" name="color_th" value="#efefef"></td>
            <td rowspan="8" style="vertical-align:top;">

                <table id="pattern" class="tlist">
                    <tr class="th">
                        <th class="th">Столбец 1</th>
                        <th class="th">Столбец 2</th>
                        <th class="th">Столбец 3</th>
                    </tr>
                    <tr class="td1">
                        <td>Цифры</td>
                        <td>123 456,78</td>
                        <td>90 987 123,00</td>
                    </tr>
                    <tr class="td2">
                        <td>Дата</td>
                        <td>05.01.2023</td>
                        <td>14.07.2023</td>
                    </tr>
                    <tr class="td1">
                        <td>Контакты</td>
                        <td>example@pochta.uz</td>
                        <td>+998 00 123 45 78</td>
                    </tr>
                    <tr class="td2">
                        <td>Данные</td>
                        <td>Маткарим Маримбоевич</td>
                        <td>ООО "NAME"</td>
                    </tr>
                </table>

            </td>
        </tr>
        <tr>
            <td>Текст шапки</td>
            <td><input type="color" id="idColor_th_text" name="color_th_text" value="#000000"></td>
        </tr>
        <tr>
            <td>Нечётные строки</td>
            <td><input type="color" id="idColor_td1" name="color_td1" value="#f7f7f7"></td>
        </tr>
        <tr>
            <td>Текст нечётных строк</td>
            <td><input type="color" id="idColor_td1_text" name="color_td1_text" value="#000000"></td>
        </tr>
        <tr>
            <td>Чётные строки</td>
            <td><input type="color" id="idColor_td2" name="color_td2" value="#ffffff"></td>
        </tr>
        <tr>
            <td>Текст чётных строк</td>
            <td><input type="color" id="idColor_td2_text" name="color_td2_text" value="#000000"></td>
        </tr>
        <tr>
            <td>Название стиля</td>
            <td><input type="text" name="theme_name"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Сохранить" name="save_theme_btn"></td>
            <td></td>
        </tr>
    </table>
</form>