Javascript 下拉菜单未出现在特定按钮下方
我目前正在制作一个下拉菜单(用于学校的活动)。虽然出于某种原因,菜单可以工作,但它只出现在第一个按钮的下方 小提琴: HTML:Javascript 下拉菜单未出现在特定按钮下方,javascript,html,css,Javascript,Html,Css,我目前正在制作一个下拉菜单(用于学校的活动)。虽然出于某种原因,菜单可以工作,但它只出现在第一个按钮的下方 小提琴: HTML: GPU制造商 CPU制造商 RAM制造商 您要做的是相对于按钮定位下拉元素 一种方法是计算按钮的位置和高度。然后定位下拉列表 // Here we select all the elements const drop = document.querySelector(".drop"); const drop1 = document.querySe
GPU制造商
CPU制造商
RAM制造商
您要做的是相对于按钮定位下拉元素
一种方法是计算按钮的位置和高度。然后定位下拉列表
// Here we select all the elements
const drop = document.querySelector(".drop");
const drop1 = document.querySelector('.drop1')
const drop2 = document.querySelector('.drop2')
const dropDown = document.getElementById("dropDown");
const dropDown1 = document.getElementById("dropDown1")
const dropDown2 = document.getElementById("dropDown2")
//Here we add a click event to the button
drop.addEventListener('click', (evt) => {
//Here we get the Left and Top position of the button
const x = evt.target.offsetLeft
const y = evt.target.offsetTop
//Here we get the height of the button
const height = evt.target.offsetHeight
dropDown.classList.toggle("show")
//And here we position the dropdown relative to the button
dropDown.style.top = `${y + height}px`
dropDown.style.left = `${x}px`
})
drop1.addEventListener('click', (evt) => {
const x = evt.target.offsetLeft
const y = evt.target.offsetTop
const height = evt.target.offsetHeight
dropDown1.classList.toggle("show")
dropDown1.style.top = `${y + height}px`
dropDown1.style.left = `${x}px`
})
drop2.addEventListener('click', (evt) => {
const x = evt.target.offsetLeft
const y = evt.target.offsetTop
const height = evt.target.offsetHeight
dropDown2.classList.toggle("show")
dropDown2.style.top = `${y + height}px`
dropDown2.style.left = `${x}px`
})