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
119 views
in Technique[技术] by (71.8m points)

html - Javascript popup?

So what I'm trying to make is a map of Germany with markers. and when clicked on a marker a div (content) will show with some things in it

is there a way to let JavaScript know which marker I clicked and it will open the corresponding content div, in total it will be about 200 markers so it must be a decently efficient code and my knowledge about JavaScript is not that great

this is the code I have for now

<div class="map">
  <img src="/images/map.jpg">
</div>

<div class="markers" style="top: 60%; left: 35%;">
  <div class="content" style="display: none;">
    <h1>Test</h1>
    <p>test</p>
  </div>
</div>

<div class="markers" style="top: 20%; left: 60%;">
  <div class="content" style="display: none;">
    <h1>Test2</h1>
    <p>test2</p>
  </div>
</div>
question from:https://stackoverflow.com/questions/65938499/javascript-popup

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

1 Reply

0 votes
by (71.8m points)

Basic idea is using event delegation and listen to the click on the parent. You can than determine what was clicked and you can toggle a class to show the hidden element. Basic idea:

document.querySelector(".map-wrapper").addEventListener("click", function (e) {
  // find if a marker was clicked
  var marker = e.target.closest('.marker');
  console.log(marker)
  // was one clicked?
  if (marker) {
    // Hide any others that may be showing
    var active = document.querySelector('.marker.active');
    if(active && active!==marker) {
      active.classList.remove('active');
    }
    // toggle the info so it shows/hides
    marker.classList.toggle('active');
  }
});
.map-wrapper {
  position: relative;
  background-color: #CCCCCC;
  width: 400px;
  height: 400px;
}

.marker {
  position: relative;
}

.marker::after {
  content: '??';
}

.marker .content {
  display: none;
  opacity: 0;
}

.marker.active .content {
  position: absolute;
  display: block;
  opacity: 1;
  transition: opacity 0.3s;
  background-color: #CCFF00;
  border: 2px solid red;
  margin: 20px;

}
<div class="map-wrapper">
  <div class="marker" style="left:100px; top: 100px;">
    <div class="content">
      <h1>Test1</h1>
      <p>test1</p>
    </div>
  </div>
  <div class="marker" style="left:150px; top: 270px;">
    <div class="content">
      <h1>Test2</h1>
      <p>test2</p>
    </div>
  </div>
  <div class="marker" style="left: 46px; top: 143px;">
    <div class="content">
      <h1>Test3</h1>
      <p>test3</p>
    </div>
  </div>

</div>

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

...