歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> HTML5之鼠標拖動圖片

HTML5之鼠標拖動圖片

日期:2017/3/1 10:51:18   编辑:Linux編程
本文實現了在HTML5的頁面裡拖動圖片。要點在於圖片被imageDIV包含,通過鼠標事件修改imageDIV的位置。下面是全部HTML5代碼:
cheungmine, 2011
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>HTML5 drag image in page - cheungmine</title>
  6. <style rel="stylesheet" type="text/css" >
  7. #_outerDiv{
  8. height:400px;
  9. width:500px;
  10. border:1px solid black;
  11. position:relative;
  12. overflow:hidden;
  13. }
  14. </style>
  15. <script type="text/javascript">
  16. function getElem (id) {
  17. return document.getElementById(id);
  18. }
  19. function trimPX (_px) {
  20. if(_px==null || _px=="")
  21. return 0;
  22. return parseInt(_px.substr(0, _px.lastIndexOf("px")));
  23. }
  24. function hitInRect (hitX, hitY, rcLeft, rcTop, rcWidth, rcHeight) {
  25. return (hitX>=rcLeft && hitX<rcLeft+rcWidth && hitY>=rcTop && hitY<rcTop+rcHeight);
  26. }
  27. function outerDiv () {
  28. return getElem("_outerDiv");
  29. }
  30. function imageDiv () {
  31. return getElem("_imageDiv");
  32. }
  33. var dragging = false;
  34. var startTop = 0; // top is a Key Word in Chrome and Opera
  35. var startLeft = 0;
  36. var dragPosY = 0;
  37. var dragPosX = 0;
  38. window.addEventListener("load", initPage, false);
  39. function initPage () {
  40. outerDiv().addEventListener("mousedown", // start moving image
  41. function (event) {
  42. startTop = trimPX(imageDiv().style.top);
  43. startLeft = trimPX(imageDiv().style.left);
  44. var width = trimPX(imageDiv().style.width);
  45. var height = trimPX(imageDiv().style.height);
  46. if (hitInRect(event.clientX, event.clientY, startLeft, startTop, width, height)) {
  47. dragging = true;
  48. dragPosX = event.clientX;
  49. dragPosY = event.clientY;
  50. event.preventDefault(); // disable default behavior of browser
  51. }
  52. },
  53. false
  54. );
  55. outerDiv().addEventListener("mousemove", // moving image
  56. function (event) {
  57. if (dragging){
  58. imageDiv().style.cursor="pointer";
  59. imageDiv().style.top = parseInt(startTop)+(event.clientY - dragPosY) + "px";
  60. imageDiv().style.left = parseInt(startLeft)+(event.clientX - dragPosX) + "px";
  61. }
  62. event.preventDefault();
  63. },
  64. false
  65. );
  66. outerDiv().addEventListener("mouseup", // stop moving image
  67. function (event) {
  68. dragging = false;
  69. imageDiv().style.cursor="default";
  70. event.preventDefault();
  71. },
  72. false
  73. );
  74. }
  75. </script>
  76. </head>
  77. <body>
  78. <div id="_outerDiv">
  79. <div id="_imageDiv" style="z-index:0; position:relative; top:0px; left:0px; width:200px; height:150px;">
  80. <img id="_imageObj" src="http://avatar.csdn.net/E/3/5/1_cheungmine.jpg"></img>
  81. </div>
  82. </div>
  83. </body>
  84. </html>
本文在Chrome, FireFox,Opera測試通過。不支持IE。
Copyright © Linux教程網 All Rights Reserved