84 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-10-17 19:49:06 +03:00
// Создание селектора
2022-10-10 20:05:02 +03:00
export function createSelected(element, content, styles) {
if (content) {
element.innerHTML = `
<div class="cg-select">
<p class="selected">${content}</p>
<div class="caret"></div>
</div>
2022-10-10 20:05:02 +03:00
`;
}
if (styles) {
customStyles(element, styles);
element.innerHTML = `
<div class="cg-select" style = "${styles}">
<span class="selected" style = "${styles}">${content}</span>
<div class="caret" style = "${styles}"></div>
</div>
2022-10-10 20:05:02 +03:00
`;
}
}
2022-10-17 19:49:06 +03:00
// Метод ищет и стилизует полученные елементы из styles
2022-10-10 20:05:02 +03:00
export function customStyles(element, styles) {
if (!styles) {
return;
}
const { head, caret, placeholder } = styles;
2022-10-12 14:36:49 +03:00
const cgSelect = element.querySelector('.cg-select');
const caretSelect = element.querySelector('.caret');
const placeholderSelect = element.querySelector('.selected');
2022-10-10 20:05:02 +03:00
customStylesFormat(head, cgSelect);
2022-10-10 20:05:02 +03:00
customStylesFormat(caret, caretSelect);
2022-10-10 20:05:02 +03:00
if (placeholderSelect) {
customStylesFormat(placeholder, placeholderSelect);
2022-10-10 20:05:02 +03:00
}
}
2022-10-17 19:49:06 +03:00
// Метод checkItemStruct возвращает true/false если item содержит указанные свойства,
export function checkItemStruct(item) {
if (item && typeof item !== 'object') {
return false;
}
return item.hasOwnProperty('id') && item.hasOwnProperty('title') && item.hasOwnProperty('value');
}
2022-10-14 14:39:34 +03:00
2022-10-17 19:49:06 +03:00
// Метод getFormatItem преобразовывает каждый елемент полученный из поля Items;
2022-10-14 14:39:34 +03:00
export function getFormatItem(dataItem, index) {
const random = Math.random().toString(36).substring(2, 10);
let item = {};
if (checkItemStruct(dataItem)) {
item = {
id: dataItem.id,
title: dataItem.title,
value: index,
};
} else {
item = {
id: random,
title: dataItem,
value: index,
};
}
return item;
}
2022-10-17 19:49:06 +03:00
// Универсальный метод для стилизации селекта
export function customStylesFormat(elemOption, selector) {
if (elemOption) {
Object.entries(elemOption).forEach(([key, value]) => {
selector.style[key] = value;
});
}
}