در این مطلب برای تمرین بیشتر جاوا اسکریپت، اسکریپتی را می نویسیم تا از طریق آن یک منوی کشویی در HTML فقط با استفاده از جاوا اسکریپت ایجاد شود.
<style> .MainSearch{ height: 50px; width: 350px; background: #63cdff; text-align: center; line-height: 50px; border-radius: 5px; cursor: pointer; } #selectClass{ height: 50px; } </style> <div class="MainSearch"> <div class="qty-dropdown"> <div id="selectClassz"><i class="fal fa-users"></i></div> </div> </div> <script> class ChoosenSelect { constructor(info){ var elem = document.getElementById(info.selector); if (elem){ var selectHeight = ''; if (info.height){ selectHeight = info.height; } else if (elem.offsetHeight) { selectHeight = elem.offsetHeight + 'px'; }else{ selectHeight = "50px"; } var span = document.createElement("span"); span.innerHTML = info.placeholder; elem.appendChild(span); var input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", info.name); elem.parentElement.appendChild(input); var itemsParent = document.createElement("div"); itemsParent.classList.add("dropdown-content"); for (let j=0; j < info.itemz.length;j++) { var item = document.createElement("div"); item.style.cssText = "line-height: "+ selectHeight +";height: 0px;background: rgba(76, 76, 77, 0.2);border-radius: 5px;transition: .2s;opacity: 0;"; item.dataset.way = info.itemz[j]; item.innerHTML = info.itemz[j]; itemsParent.appendChild(item); } elem.parentElement.appendChild(itemsParent); elem.addEventListener("click",function () { this.classList.toggle("active"); if(this.classList.contains("active")){ for (let i=0 ; i < itemsParent.children.length ; i++){ itemsParent.children[i].style.height = selectHeight; itemsParent.children[i].style.opacity = "1"; itemsParent.children[i].addEventListener("click",clickEven) } }else{ for (let i=0 ; i < itemsParent.children.length ; i++){ itemsParent.children[i].style.height = "0px"; itemsParent.children[i].style.opacity = "0" } } }); function clickEven() { input.value = this.dataset.way; for (let i=0 ; i < itemsParent.children.length ; i++){ itemsParent.children[i].style.height = "0px"; itemsParent.children[i].style.opacity = "0"; } elem.classList.remove("active"); elem.querySelector("span").textContent = this.dataset.way; } } } } var choosen = new ChoosenSelect({ placeholder:"Select Studio", name:"class", selector: "selectClassz", itemz:['Mono','Sterio','dulby','Rounded','miomio'], height:"50px" }); // console.log(choosen); </script>
دیدگاه ها :