用javascript在图像上拖动和绘制矩形的解决方案

经过几个小时的搜索和编码,我终于有了在图像上拖动和绘制矩形的代码.我从一篇两年前的帖子中获得了下面粘贴的大部分代码,并对其进行了一些修补工作.现在它同时支持Firefox和IE7.但在IE7上,它有一个小缺陷……但仍然可以工作.一旦我有了答案,我会尽快发布补丁.给你们,伙计们

选择 | 换行 | 行号
  1. <HTML>
  2. <HEAD>
  3. <META http-equiv=imagetoolbar content=no>
  4. <TITLE>
  5.  
  6. </TITLE>
  7. <STYLE>
  8. #rubberBand {
  9. position: absolute;
  10. visibility: hidden;
  11. width: 0px; height: 0px;
  12. border: 2px solid red;
  13. }
  14. </STYLE>
  15.  
  16. </HEAD>
  17. <BODY>
  18. <img name="myImage" id="myImage" src="VK.jpg" height=400
  19. width=400>
  20.  
  21.  
  22. <DIV ID="rubberBand"></DIV>
  23.  
  24. <SCRIPT>
  25.  
  26. var IMG;
  27.  
  28. function startRubber (evt) {
  29. if (document.all) {
  30. // IE
  31. var r = document.all.rubberBand;
  32. r.style.width = 0;
  33. r.style.height = 0;
  34. r.style.pixelLeft = event.x;
  35. r.style.pixelTop = event.y;
  36. r.style.visibility = 'visible';
  37. IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
  38. }
  39. else if (document.getElementById) {
  40. // firefox
  41. evt.preventDefault();
  42. var r = document.getElementById('rubberBand');
  43. r.style.width = 0;
  44. r.style.height = 0;
  45. r.style.left = evt.clientX + 'px';
  46. r.style.top = evt.clientY + 'px';
  47. r.style.visibility = 'visible';
  48. r.onmouseup = stopRubber;
  49. }
  50. IMG.onmousemove = moveRubber;
  51. }
  52. function moveRubber (evt) {
  53. if (document.all) { // IE
  54. var r = document.all.rubberBand;
  55. r.style.width = event.x - r.style.pixelLeft;
  56. r.style.height = event.y - r.style.pixelTop;
  57. }
  58. else if (document.getElementById) { // firefox
  59. var r = document.getElementById('rubberBand');
  60. r.style.width = evt.clientX - parseInt(r.style.left);
  61. r.style.height = evt.clientY - parseInt(r.style.top);
  62. }
  63. return false; // otherwise IE won't fire mouseup :/
  64. }
  65. function stopRubber (evt) {
  66. IMG.onmousemove = null;
  67. }
  68.  
  69. function cancelDragDrop()
  70. {
  71. window.event.returnValue = false;
  72. }
  73.  
  74. IMG = document.getElementById('myImage');
  75. IMG.onmousedown = startRubber;
  76. IMG.onmouseup = stopRubber;
  77.  
  78. </SCRIPT>
  79. </BODY>
  80. </HTML>
  81.  

--由IAM_Clint编辑:感谢您的帖子,可能会将它的一个例子的链接放在行动中.

# 回答1


要在较新版本的Firefox中工作,在该版本中拖回矩形(使其变小)会导致事件流向您想要的"带",请添加以下代码:

选择 | 换行 | 行号
  1. var band =  document.getElementById('rubberBand');
  2. band.onmousemove = moveRubber;
  3.  

标签: Javascript

添加新评论