Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

javascript - How to create menu responsive on click or on hover depend on device?

I was creating a button with a and what I wanted is when I'm on a mobile device, I can click on the button and the menu appears. As we know, we can't hover on mobile devices But on a tab and higher devices, the menu should display on hover, not on click. codepen If I use onclick for mobile devices, then the menu stays on medium and above devices and If I remove onclick to work properly on medium and above devices then on mobile we can't click, as the only option left to open the menu is hover which we can't do in mobile devices. How to solve this problem. The only goal is to make a responsive design.

const btn = document.querySelector('.btn');
const list = document.querySelector('.list');

btn.addEventListener('click', () => {
  list.style.display = 'block';
})
.btn{
  margin: 0;
  display: block;
  width: 100%;
  padding: 1rem;
  background-color: teal;
  color: white;
  font-size: 2rem;
  border-radius: 8px;
}

.list{
  display: none;
}

.btn:hover + .list{
    display: block;
  }
}

@media (min-width: 768px) {
  .btn{
    width: 50%;
  }
}
<a class="btn"> Names </a>

<ul class="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
question from:https://stackoverflow.com/questions/65842156/how-to-create-menu-responsive-on-click-or-on-hover-depend-on-device

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you go read about media queries in JavaScript and you can put a different onClick even based on the size of the window: https://www.w3schools.com/howto/howto_js_media_queries.asp


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...