首页 > 解决方案 > 如何设置此标记的不透明度

问题描述

如何根据弹出窗口中选定的单选选项切换此标记的不透明度?

L.marker([-14.604847, 30.234375],)
   .bindPopup('<input type="radio" id="on" name="switch" value="on"><label for="on">ON</label><input type="radio" id="off" name="gender" value="off">
<label for="off">OFF</label><input type="radio" id="other" name="switch" value="other">')
   .addTo(map);

例如,我单击“打开”,然后标记的不透明度更改为 1,当我单击关闭时,它更改为不透明度 0.3

标签: leaflet

解决方案


获取标记的参考,监听popupopen事件,然后使用 L.DomEvent每个复选框更改事件进行监听。一旦开启,将标记不透明度设置为 1,一旦关闭,将其设置为 0.3。我相信它可以用更少的代码来实现,但它可以让你开始。

 marker.on('popupopen', function(popup) {
    L.DomEvent.on(
      document.getElementById('off'),
      'change',
      (ev) => marker.setOpacity(0.3));
    L.DomEvent.on(
      document.getElementById('on'),
      'change',
      (ev) => marker.setOpacity(1));
 })

<!DOCTYPE html>
<html>

<head>

  <title>Quick Start - Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>



</head>

<body>



  <div id="map" style="width: 600px; height: 400px;"></div>
  <script>
    var map = L.map('map').setView([-14.604847, 30.234375], 13);

    L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
      maxZoom: 18,
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' +
        'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
      id: 'mapbox/streets-v11',
      tileSize: 512,
      zoomOffset: -1
    }).addTo(map);


    const marker = L.marker([-14.604847, 30.234375])
      .bindPopup('<input type="radio" id="on" name="switch" value="on"><label for="male">ON</label><br><input type="radio" id="off" name="switch" value="off"><label for="female">OFF</label>')
      .addTo(map)




    marker.on('popupopen', function(popup) {
      L.DomEvent.on(
        document.getElementById('off'),
        'change',
        (ev) => marker.setOpacity(0.3));
      L.DomEvent.on(
        document.getElementById('on'),
        'change',
        (ev) => marker.setOpacity(1));
    })
  </script>



</body>

</html>


推荐阅读