js事件应用(事件绑定、拖拽吸附、事件捕获)

待我称王封你为后i 2024-02-17 23:23 171阅读 0赞

案例1:事件绑定:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <script>function myAddEvent(obj, ev, fn) {
  7. if(obj.attachEvent) {
  8. //IE下
  9. //attachEvent(事件名,函数);
  10. //detachEvent() 解除绑定
  11. obj.attachEvent('on' + ev, fn);
  12. } else {
  13. //FF Chrome下
  14. //addEventListener(事件名,函数,false);
  15. //removeEventListener()解除绑定
  16. obj.addEventListener(ev, fn, false);
  17. }
  18. }
  19. window.onclick = function() {
  20. var oBtn = document.getElementById("btn1");
  21. myAddEvent(oBtn, 'click', function() {
  22. alert('a');
  23. });
  24. myAddEvent(oBtn, 'click', function() {
  25. alert('b');
  26. });
  27. }</script>
  28. </head>
  29. <body>
  30. <input type="button" id = "btn1" value="按钮"/>
  31. </body>
  32. </html>

案例2:拖拽吸附

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <style>
  7. #div1 {height: 200px;width: 200px;background: red;position: absolute;}
  8. #div2 {height: 500px;width: 700px;background: gray;position:relative;}
  9. </style>
  10. <script>
  11. window.onclick = function(){
  12. var oDiv = document.getElementById("div1");
  13. var oDiv2 = document.getElementById("div2");
  14. oDiv.onmousedown = function(ev){
  15. var oEvent = ev || event;
  16. var disX = oEvent.clientX - oDiv.offsetLeft;
  17. var disY= oEvent.clientY - oDiv.offsetTop;
  18. //这里不能用oDiv,因为宽度小,当鼠标移出时就会失去效果
  19. document.onmousemove = function(ev){
  20. var oEvent = ev || event;
  21. var x = oEvent.clientX - disX;
  22. var y = oEvent.clientY - disY;
  23. //解决div跑出界面的情况
  24. if(x < 50){ //吸附原理
  25. x = 0;
  26. }
  27. else if(x > oDiv2.offsetWidth - oDiv.offsetWidth - 50){
  28. x = oDiv2.offsetWidth - oDiv.offsetWidth;
  29. }
  30. if(y < 50){
  31. y = 0;
  32. }
  33. else if(y > oDiv2.offsetHeight - oDiv.offsetHeight - 50){
  34. y = oDiv2.offsetHeight - oDiv.offsetHeight;
  35. }
  36. oDiv.style.left = x + 'px';
  37. oDiv.style.top = y + 'px';
  38. }
  39. document.onmouseup = function(){
  40. document.onmousemove = null;
  41. document.onmouseup = null;
  42. }
  43. //解决FF问题
  44. return false;
  45. }
  46. }
  47. </script>
  48. </head>
  49. <body>
  50. <div id = "div2">
  51. <div id = "div1"></div>
  52. </div>
  53. </body>
  54. </html>

案例3:事件捕获

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <script>
  7. window.onclick = function(){
  8. var oBtn = document.getElementById("btn1");
  9. oBtn.onclick = function(){
  10. alert('yes');
  11. }
  12. //IE下使用
  13. //oBtn.setCapture();
  14. //oBtn.releaseCapture();
  15. }
  16. </script>
  17. </head>
  18. <body>
  19. <input type = "button" value="按钮" id = "btn1"/>
  20. </body>
  21. </html>

发表评论

表情:
评论列表 (有 0 条评论,171人围观)

还没有评论,来说两句吧...

相关阅读