Skip to content

带无障碍地图的自定义元素 ​

带无障碍地图的自定义元素示例。 es2015 Web Component 自定义元素 Shadow DOM 无障碍 键盘焦点

本示例创建并注册了一个包含无障碍 OpenLayers 地图的自定义元素 ol-map。为此,ol-map 元素的 tabindex 属性被设置为 "0",这样地图就可以获得焦点,从而支持使用键盘进行地图导航。使用 + 和 - 键缩放地图,使用方向键平移地图。注意: 仅在支持 ShadowRoot 的浏览器中可用。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';

let map;
class OLComponent extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({mode: 'open'});
    const link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', 'theme/ol.css');
    this.shadow.appendChild(link);
    const style = document.createElement('style');
    style.innerText = `
      :host {
        display: block;
      }
    `;
    this.shadow.appendChild(style);
    const mapTarget = document.createElement('div');
    mapTarget.style.width = '100%';
    mapTarget.style.height = '100%';
    this.shadow.appendChild(mapTarget);

    this.map = new Map({
      target: mapTarget,
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      view: new View({
        center: [0, 0],
        zoom: 2,
      }),
    });
  }
}

customElements.define('ol-map', OLComponent);
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>带无障碍地图的自定义元素</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      #map:focus {
        outline: 0.15em solid #4A74A8;
      }
    </style>
  </head>
  <body>
    <ol-map id="map" class="map" tabindex="0"></ol-map>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "es2015-custom-element-a11y",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}