|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 6 | + <title>Draggable Navigation Bar</title> |
| 7 | + <style> |
| 8 | + body { |
| 9 | + font-family: Arial, sans-serif; |
| 10 | + margin: 0; |
| 11 | + padding: 0; |
| 12 | + overflow: hidden; /* Prevent scrollbars */ |
| 13 | + } |
| 14 | + |
| 15 | + .nav-bar { |
| 16 | + width: 200px; |
| 17 | + background: #007BFF; |
| 18 | + color: white; |
| 19 | + padding: 15px; |
| 20 | + border-radius: 8px; |
| 21 | + position: absolute; /* Position for dragging */ |
| 22 | + cursor: move; /* Cursor style for dragging */ |
| 23 | + } |
| 24 | + |
| 25 | + .nav-bar h2 { |
| 26 | + margin: 0 0 15px; /* Updated margin */ |
| 27 | + font-size: 18px; |
| 28 | + } |
| 29 | + |
| 30 | + .nav-bar ul { |
| 31 | + list-style-type: none; |
| 32 | + padding: 0; |
| 33 | + } |
| 34 | + |
| 35 | + .nav-bar ul li { |
| 36 | + margin: 10px 0; |
| 37 | + } |
| 38 | + |
| 39 | + .nav-bar ul li a { |
| 40 | + color: white; |
| 41 | + text-decoration: none; |
| 42 | + } |
| 43 | + </style> |
| 44 | +</head> |
| 45 | +<body> |
| 46 | + <div class="nav-bar" id="navBar"> |
| 47 | + <h2>Navigation</h2> |
| 48 | + <ul> |
| 49 | + <li><a href="#">Home</a></li> |
| 50 | + <li><a href="#">About</a></li> |
| 51 | + <li><a href="#">Services</a></li> |
| 52 | + <li><a href="#">Contact</a></li> |
| 53 | + </ul> |
| 54 | + </div> |
| 55 | + |
| 56 | + <script> |
| 57 | + const navBar = document.getElementById('navBar'); |
| 58 | + |
| 59 | + // Variables to store the current mouse position |
| 60 | + let offsetX, offsetY; |
| 61 | + |
| 62 | + navBar.addEventListener('mousedown', function(e) { |
| 63 | + // Get the current mouse position relative to the nav bar |
| 64 | + offsetX = e.clientX - navBar.getBoundingClientRect().left; |
| 65 | + offsetY = e.clientY - navBar.getBoundingClientRect().top; |
| 66 | + |
| 67 | + // Add mousemove event to the document |
| 68 | + document.addEventListener('mousemove', onMouseMove); |
| 69 | + document.addEventListener('mouseup', onMouseUp); |
| 70 | + }); |
| 71 | + |
| 72 | + function onMouseMove(e) { |
| 73 | + // Update the position of the nav bar |
| 74 | + navBar.style.left = (e.clientX - offsetX) + 'px'; |
| 75 | + navBar.style.top = (e.clientY - offsetY) + 'px'; |
| 76 | + } |
| 77 | + |
| 78 | + function onMouseUp() { |
| 79 | + // Remove mousemove and mouseup events |
| 80 | + document.removeEventListener('mousemove', onMouseMove); |
| 81 | + document.removeEventListener('mouseup', onMouseUp); |
| 82 | + } |
| 83 | + </script> |
| 84 | +</body> |
| 85 | +</html> |
0 commit comments