Page Scroll
Runnable OpenLayers example: Page Scroll. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:页面滚动中的地图
要点:去掉滚轮缩放交互,按住 Ctrl 才接管滚轮,页面本身照常滚动
依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>页面滚动中的地图</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
html,body{margin:0}
body{font:14px/1.8 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#1c2128;background:#fbfbfc}
h1{font-size:18px;margin:0;padding:18px 20px 6px}
p{padding:0 20px;color:#4a5462;margin:8px 0 16px}
#map{height:360px;position:relative;border-top:1px solid #e3e6ea;border-bottom:1px solid #e3e6ea}
.hint{position:absolute;left:12px;bottom:12px;background:rgba(255,255,255,.92);
padding:6px 10px;border-radius:6px;font-size:12px;color:#445;z-index:2;
box-shadow:0 1px 4px rgba(0,0,0,.14)}
.pad{height:900px;padding:20px}
</style>
</head>
<body>
<h1>页面滚动中的地图</h1>
<p>鼠标放在地图上滚动滚轮时,页面继续滚动;按住 Ctrl 再滚轮才缩放地图。这样地图不会拦下整页的滚动。</p>
<div id="map"><div class="hint" id="hint">滚轮滚动页面 · Ctrl + 滚轮缩放</div></div>
<div class="pad">下面的长内容用于验证页面滚动。</div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
'use strict';
if (!window.ol) {
document.getElementById('map').textContent = 'OpenLayers 加载失败,请检查 cdn.jsdelivr.net 是否可访问';
return;
}
/* 默认交互里去掉滚轮缩放,否则滚轮事件会被地图吃掉 */
var interactions = ol.interaction.defaults.defaults({
mouseWheelZoom: false,
altShiftDragRotate: false,
pinchRotate: false
});
var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) })],
view: new ol.View({ center: ol.proj.fromLonLat([116.391263, 39.907359]), zoom: 12 }),
interactions: interactions,
controls: ol.control.defaults.defaults({ rotate: false })
});
var viewport = map.getViewport();
viewport.addEventListener('wheel', function (evt) {
if (!evt.ctrlKey && !evt.metaKey) return; /* 不拦截,交给页面滚动 */
evt.preventDefault();
var view = map.getView();
var next = view.getZoom() - evt.deltaY * 0.0025;
view.setZoom(Math.max(view.getMinZoom(), Math.min(view.getMaxZoom(), next)));
document.getElementById('hint').textContent = 'Ctrl + 滚轮:当前 ' + view.getZoom().toFixed(2) + ' 级';
}, { passive: false });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.