在高德地图API中,如果你想在鼠标移入线(Polyline)时显示手指头样式(即光标变为手型),可以通过修改CSS的cursor属性来实现。你可以在鼠标移入事件中将光标设置为pointer,在鼠标移出事件中恢复为默认样式。
以下是修改后的代码示例:
修改后的代码
<div id="mapContainer" style="width: 100%; height: 500px;"></div>
<script>
// 初始化地图
var map = new AMap.Map('mapContainer', {
zoom: 13,
center: [116.397428, 39.90923] // 设置地图中心点
});
// 定义线的路径
var path = [
[116.395577, 39.892257],
[116.418261, 39.893913],
[116.418222, 39.907424]
];
// 创建线对象
var polyline = new AMap.Polyline({
path: path,
strokeColor: "#3366FF", // 线颜色
strokeWeight: 5, // 线宽
strokeStyle: "solid" // 线样式
});
// 将线添加到地图上
map.add(polyline);
// 添加移入事件
polyline.on('mouseover', function(e) {
polyline.setOptions({
strokeColor: "#FF0000", // 移入时改变线颜色
strokeWeight: 8 // 移入时改变线宽
});
// 设置光标为手型
map.getContainer().style.cursor = 'pointer';
});
// 添加移出事件
polyline.on('mouseout', function(e) {
polyline.setOptions({
strokeColor: "#3366FF", // 移出时恢复线颜色
strokeWeight: 5 // 移出时恢复线宽
});
// 恢复光标为默认样式
map.getContainer().style.cursor = 'default';
});
</script>
关键点解释
-
map.getContainer().style.cursor:map.getContainer()获取地图的容器(即地图的DOM元素)。- 通过修改
style.cursor属性,可以改变光标样式。 pointer是CSS中表示手型光标的属性值。
-
鼠标移入事件:
- 在
mouseover事件中,将光标设置为pointer,表示手型。
- 在
-
鼠标移出事件:
- 在
mouseout事件中,将光标恢复为default,表示默认样式。
- 在
效果
- 当鼠标移入线时,线的颜色和宽度会发生变化,同时光标会变成手型。
- 当鼠标移出线时,线的样式恢复,光标也会恢复为默认样式。
其他光标样式
如果你想要其他光标样式,可以参考CSS的cursor属性值,例如:
default:默认箭头pointer:手型move:移动crosshair:十字text:文本输入wait:等待- 等等。
通过这种方式,你可以轻松地为高德地图上的线添加手指头样式或其他光标效果。