初学者在简单的下拉菜单中苦苦挣扎

时间:2017-03-06 04:12:55

标签: javascript html html5

具体来说,我正在尝试制作一个下拉菜单,其中包含指向点击时指向谷歌地图中指定位置的链接。我设法将谷歌地图嵌入到我的页面中,但由于某种原因,我似乎无法让下拉发生并且无法在我的代码中找到问题。我也很难理解如何在下拉菜单中实际创建链接以指向谷歌地图上的选定位置。任何帮助,将不胜感激。我到目前为止的代码......

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show')
      }
    }
  }
}

function initMap() {
  var Columbia = {
    lat: 34.006140,
    lng: -81.037532
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: Columbia
  });
  var marker = new google.maps.Marker({
    position: Columbia,
    map: map
  });
}
.dropbtn {
  background-color: #4caf50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover,
.dropbtn:focus {
  background-color: #3e8e41;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #f1f1f1
}

#map {
  height: 400px;
  width: 100%;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5cD8oVYji2MWCAj8JzrAzQtpBy12W30o&callback=initMap">
</script>
<h3>Google Maps/Form Assignment</h3>
<div id="map"></div>
<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Select a location</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#london">London, England</a>
    <a href="#tokyo">Tokyo, Japan</a>
    <a href="#newyork">New York City, USA</a>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

我看到你为同一个进程添加了2个不同的函数,你只需要1,所以我将显示带有修复的代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        .dropbtn {
            background-color: #4caf50;
            color: white;
            padding: 16px;
            font-size: 16px;
            border: none;
            cursor: pointer;
        }
        .dropbtn:hover, .dropbtn:focus{
            background-color: #3e8e41;
        }
        .dropdown{
            position: relative;
            display: inline-block;
        }
        .dropdown-content{
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            overflow: auto;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
            z-index: 1;
        }
        /*Add this rule so the dropdown can be shown*/
        .dropdown-content.show{
            display: block;
        }
        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
        .dropdown a:hover {
            background-color: #f1f1f1
        }
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>
    <h3>Google Maps/Form Assignment</h3>
    <div id="map"></div>
    <div class="dropdown">
        <button class="dropbtn">Select a location</button>
        <div id="myDropdown" class="dropdown-content">
            <a href="#london">London, England</a>
            <a href="#tokyo">Tokyo, Japan</a>
            <a href="#newyork">New York City, USA</a>
        </div>
    </div>

    <script>
        window.onclick = function(event){
            var target = event.target;

            if(target.matches('.dropbtn')){
                var dropdowns = document.getElementsByClassName("dropdown-content"); //This returns a HTMLCollection

                for(i=0; i < dropdowns.length; i++){
                    // Since dropdowns is a HTMLCollection, extract the node from the collection
                    var dropdown = dropdowns.item(i);

                    // Toggle the dropdown whenever the button is clicked
                    dropdown.classList.toggle("show");
                }
            }

            if(target.matches(".dropdown-content > a")){
                // Get the location name from the hash
                var location = target.hash.slice(1);

                // Extract the location map and set it as center
                map.setCenter(positions[location]);
            }
        };
        </script>
        <script>
            function initMap() {
                // Set all locations map
                window.positions = {
                    london: {
                        lat: 51.5013616,
                        lng: -0.1965444
                    },
                    southCarolina: {
                        lat: 34.006140,
                        lng: -81.037532
                    } 
                };

                window.map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 4,
                    center: positions.southCarolina
                });

                // Add marker positions in the map
                var markers = {
                    london: new google.maps.Marker({
                        position: positions.london,
                        map: map
                    }),
                    southCarolina: new google.maps.Marker({
                        position: positions.southCarolina,
                        map: map
                    })
                };
            }

    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB5cD8oVYji2MWCAj8JzrAzQtpBy12W30o&callback=initMap">
    </script>
</body>
</html>

我在评论中添加了应该与您的代码区别开来的内容。

您需要知道document.getElementsByClassName会返回仅HTMLCollection作为属性的length对象以及itemnamedItem的2种方法,您可以请参阅HTMLCollection的文档和getElementsByClassName

的文档

编辑:我还添加了一个部分代码,用于在点击下拉项时处理地图位置视图,请注意我刚添加了london的示例,因此您可以继续执行休息其他地方