用jq封装元素拖拽和键盘控制元素移动的效果

    科技2023-11-11  97

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 150px; height: 150px; background-color: red; position: absolute; left: 0; top: 0; } </style> </head> <body> <!-- 要求:JQ编写同一个元素既可以被鼠标拖拽,又可以上下左右控制元素移动 --> <div></div> <script src="jquery-1.10.1.min.js"></script> <script> $("div").mousedown(function (ev){ var disX = ev.pageX - $("div").offset().left; var disY = ev.pageY - $("div").offset().top; $(document).on("mousemove",function (ev){ $("div").css({ "left" : ev.pageX - disX + "px", "top" : ev.pageY - disY + "px", }) }) $(document).on("mouseup",function (){ $(document).off("mousemove mouseup"); }) }) $(document).keydown(function (ev){ // console.log(ev.which); switch(ev.which){ //相当于原生中event.keyCode(获取键盘值) case 37 : $("div").css("left",$("div").offset().left - 3 + "px"); break; case 38 : $("div").css("top",$("div").offset().top - 3 + "px"); break; case 39 : $("div").css("left",$("div").offset().left + 3 + "px"); break; case 40 : $("div").css("top",$("div").offset().top + 3 + "px"); break; } }) </script> </body> </html>
    Processed: 0.013, SQL: 8