weixin_57556590 2021-04-22 22:27 采纳率: 100%
浏览 219
已采纳

onmousemove事件触发一次后无法再触发

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.w{
				position: absolute;margin: auto;left: 20%;top: 35%;
			}
			.t{
				width: 160px;
				height: 220px;
				background-color: pink;
				position: fixed;top: 20px;
			}
			.b{
				width: 180px;
				height: 80px;
				background-color: #7FFFD4;
			}
		</style>
	</head>
	<body>
		<div>
			<div class="w">
				<div class="t" id="t" ></div>
				<div class="b"></div>
			</div>
		</div>
		<script type="text/javascript">
			var t = document.getElementById('t')
		
			var boxC,mouseC;

			t.onmousedown = function () {
				
				boxC = t.style.top
				mouseC = event.clientY
				
				t.onmousemove = function(){
				
					// t.style.top = event.clientY - 100 + 'px'
					t.style.top = boxC + (event.clientY - mouseC) + 'px'
				
					
				}
				
			}
			t.onmouseup = function(){
				t.onmousemove = null
				

			}
		</script>
	</body>
</html>

前端小白,想写一个拖拽效果,但是拖拽一次后就无法再拖拽

  • 写回答

1条回答 默认 最新

  • weixin_57556590 2021-04-23 01:26
    关注

    找到问题了,style对象不能获取css里的值

    第一次拖拽boxC的值为空因此不影响整条式子的运算

    第二次拖拽时boxC已经有了值,并且为px单位因此无法与值为数字的(event.clientY - mouseC)进行运算导致无法拖拽

    由于一次拖拽boxC的值为空因此parseInt(boxC)会导致无法运行

    解决方案为为在事件外侧加上 t.style.top = '20px',运算中的boxC改为parseInt(boxC)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置