0

在下面的代码中,我试图在用户单击文本字段时显示 ul 元素,并在用户单击 div 之外的某个位置时隐藏它,除了出现问题外,它工作得很好。ul 元素将被隐藏我单击一个标签元素(共享我的位置),但我没有在控制台中获得坐标。你知道我的错误在哪里吗?

HTML 代码:

<div id="location">
      <input id="where" type="text" maxlength="100" name="r" />
      <hr>
      <ul class="location-popup">
        <li>
          <a id="#share">&nbsp;Share my Location</a>
        </li>
      </ul>
</div>

CSS:

.location-popup
 {
           display: none;
           padding: 15px;
           height: 50px;
           line-height: 30px;
           list-style-type: none;
           background-color: white;
           text-decoration: none; 

           a {
                font-size: 20px;
                padding-bottom: 15px;
                color: black;
                cursor: pointer;
              }
    }  
hr  {
      display: none;
      height: 0;
      padding: 0;
      margin: 0;
      position: absolute;
      border-color: #009fda;
      border-style: solid none none none;
      border-width: 1px;
      left: 15px;
      right: 15px;
    }

    div#location {
      border: 1px solid #009fda;
      border-radius: 3px;
      position: relative;
    }

    input#where {
      width: 100%;
      max-width: none !important;
      height: 68px;
      margin-bottom: 0;
      line-height: 50px;
      border: 1px solid #009fda;
      padding: 0px 15px;
      border: none;
      font-size: 20px;
      text-indent: 15px;
      outline: none;
    }

jQuery代码:

    $(function() {
      $('#share').click(function() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(location) {
            console.log(location.coords.latitude);
            console.log(location.coords.longitude);
            console.log(location.coords.accuracy);
          });
        } else {
          console.log("Geolocation is not supported by this browser.");
        }
      });

      $("#where").click(function() {
        $('.location-popup').show();
        $('hr').show();
      });

      $("#where").keyup(function() {
        if ($("#where").val().length > 2) {
          $('.location-popup').hide();
          $('hr').hide();
        }
      });

      $('#location').focusout(function() {
        $('.location-popup').hide();
        $('hr').hide();
      });
    });

演示看这里

4

1 回答 1

0

可能你的 UI 搞砸了。我保留了一个最小的用户界面,并且效果很好。


      <a id="share">&nbsp;Share my Location</a>
      <p id="coords">

      </p>

  var coords = document.querySelector('#coords');
  $('#share').click(function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(location) {
        coords.innerHTML = location.coords.latitude+"\n"+location.coords.longitude;
      });
    } else {
      console.log("Geolocation is not supported by this browser.");
    }
  });

JSfiddle

于 2019-09-14T11:08:27.097 回答