【JS】动态添加的元素绑定点击事件在移动端不生效

问题:使用js动态添加的元素,给该元素绑定了点击事件,在PC端一切正常触发,但是在移动端却无法触发方法。

原因:在移动端,绑定点击事件需要注意使用 touch 事件,而不是鼠标的 click 事件。

常用的触摸事件有:- touchstart:手指触摸屏幕时触发
- touchmove:手指滑动屏幕时连续触发
- touchend:手指离开屏幕时触发

- 避免使用click事件,这是为鼠标设计的
- 对于触屏设备,要区分不同手指的触摸事件
- 可以同时绑定touch和click事件,实现移动端和PC端的兼容

// 方法一:通过addEventListener绑定
element.addEventListener('touchstart', function(){
  //点击处理
}, false); 

// 方法二:直接内联绑定
<div ontouchstart="touch(event)"></div>  

function touch(event) {
  // 点击处理
}

 蜂鸟视图的室内地图动态添加的DomMarker无法在移动端进行点击触发的解决方法

		// 显示选择起点终点的选项卡
		function showDomMarker(position) {
			if (domMarker) {
				domMarker.remove();
				domMarker = null;
			}
			domMarker = new fengmap.FMDomMarker({
				x: position.x,
				y: position.y,
				domHeight: 80,
				domWidth: 200,
				anchor: fengmap.FMMarkerAnchor.BOTTOM,
				content: `<div style=" display: inline-block; width: 200px; text-align: center;">
		<div style="display: flex;margin-bottom: 10px; border-radius: 6px; background-color: white; text-align: center;">
			<span id="clickStart" style="flex: 1; height: 30px; color: white;padding: 10px 16px; line-height: 30px; background-color: #2F65EE; border-bottom-left-radius: 6px; border-top-left-radius:6px; " onclick=setStart() ontouchstart=setStart()>作为起点</span>
			<span style="flex: 1; height: 30px; padding: 10px 16px; line-height: 30px;" onclick=setEnd() ontouchstart=setEnd()>作为终点</span>
		</div>
		<div style="background-image: url('https://developer.fengmap.com/fmAPI/images/navi/marker.png');display: inline-block; width: 32px; height: 32px;background-size:100%;"></div>
		</div>`,
			});
			var level = position.level;
			var floor = map.getFloor(level);
			domMarker.addTo(floor);
		}

猜你喜欢

转载自blog.csdn.net/liusuihong919520/article/details/131698929
今日推荐