Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - How to use hover with a link id and a div id

I am trying to create a mega menu with html and css. The dropdown has 2 columns, and I am trying to show different outputs on the right when I hover a link from the left column.

Here is my HTML code:

.column-right {
  visibility: hidden;
  float: left;
  width: 80%;
  padding: 10px;
  background-color: #ccc;
  height: 250px;
}

#firstleft:hover #first {
  visibility: visible;
}
<div class="column-left">
  <h3>Category 1</h3>
  <a id="firstleft" href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>
<div id="first" class="column-right">
  <h3>Category 2</h3>
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>

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

1 Answer

0 votes
by (71.8m points)

Cascading Style Sheets, which means that CSS can't target parent selectors as it always executes styles down the DOM Tree.

Fortunately, there's a very easy Javascript fix that requires very little code:

const hoverlink = document.querySelector('#firstleft')
const column_right = document.querySelector('#first')
// Show column
hoverlink.addEventListener('mouseover', () => {
  column_right.style.visibility = 'visible';
})
column_right.addEventListener('mouseover', () => {
  column_right.style.visibility = 'visible';
})
// Hide column
hoverlink.addEventListener('mouseout', () => {
  column_right.style.visibility = 'hidden';
})
column_right.addEventListener('mouseout', () => {
  column_right.style.visibility = 'hidden';
})
.column-right {
  visibility: hidden;
  float: left;
  width: 80%;
  padding: 10px;
  background-color: #ccc;
  height: 250px;
}
<div class="column-left">
  <h3>Category 1</h3>
  <a id="firstleft" href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>
<div id="first" class="column-right">
  <h3>Category 2</h3>
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...