我有一個(gè)基本的輸入和標(biāo)籤:https://codepen.io/agrawalishaan/pen/QWBxBdK
span { border: 1px solid red; }
<label for="myInput"> I am a label! <span>icon</span> </label> <input id="myInput"/>
當(dāng)我點(diǎn)擊標(biāo)籤時(shí),遊標(biāo)設(shè)定在輸入內(nèi)部,這是理想的。
我的標(biāo)籤還包含一個(gè)資訊圖示。當(dāng)我將滑鼠懸停在該圖示上時(shí),會(huì)出現(xiàn)一個(gè)彈出視窗(因此我需要 hover
才能工作)。
在行動(dòng)裝置上,沒(méi)有懸停,而是需要點(diǎn)擊。但是,當(dāng)我點(diǎn)擊此圖示時(shí),會(huì)出現(xiàn)彈出視窗並選擇輸入,如何在僅單擊該圖示時(shí)專(zhuān)門(mén)停用輸入選擇?
我新增了一些使用 event.preventDefault() 方法的 JavaScript,以確保在點(diǎn)擊圖示時(shí)輸入不會(huì)獲得焦點(diǎn)。
const infoIcon = document.querySelector('.info-icon'); const popup = document.querySelector('#popup'); infoIcon.addEventListener('click', function(event) { event.preventDefault(); // prevent default behavior of focusing on the input //toggles the popup on click/touch of the icon popup.style.display = popup.style.display === 'none' ? 'block' : 'none' });
span { border: 1px solid red; } #popup { position:absolute; display:none; width:50px; height:50px; border-style:solid; background-color:yellow; } .info-icon:hover #popup { /*uses the ' ' adjacent child selector to display popup on hover*/ display: block; }