直接复制代码运行就对了!!!
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>【经典】原生JS实现“用鼠标拖拽(drag)内容DIV”,滚动条对应同步滚动</title> <style> /*滚动条样式----------------------------------------*/ /*滚动条轨道*/ ::-webkit-scrollbar { width: 8px; height: 8px; background: #00000011; } /*滚动条滑块*/ ::-webkit-scrollbar-thumb { border-radius: 8px; background: #00000033; } /*移入滑块*/ ::-webkit-scrollbar-thumb:hover { background: #00000055; } /*拐角处*/ ::-webkit-scrollbar-corner { background: none; } /*----------------------------------------*/ .scrollContainer { width: 900px; height: 400px; overflow: auto; } .dragContainer { width: 1200px; height: 600px; display: flex; justify-content: center; align-items: center; } .dragContainer p { width: 500px; font-size: 40px; font-weight: bold; padding: 50px; border-radius: 50px; background-color: #409EFF; color: white; } /*核心样式----------------------------------------*/ .dragContainer { cursor: grab; } .dragContainer:active { cursor: grabbing; user-select: none; } /* ---------------------------------------- */ </style> </head> <body> <div class="scrollContainer"> <div class="dragContainer"> <p>这里的文字是可以拖拽的,可以左右上下拖拽,水平垂直滚动条也会对应滚动!拖拽的幅度和滚动条移动的幅度是对应等比例的!</p> </div> </div> </body> <script> let scrollContainer = document.querySelector(".scrollContainer"); let dragContainer = document.querySelector(".dragContainer"); dragContainer.onmousedown = e => { //鼠标按下那一刻,滚动条的位置 let mouseDownScrollPosition = { scrollLeft: scrollContainer.scrollLeft, scrollTop: scrollContainer.scrollTop }; //鼠标按下的位置坐标 let mouseDownPoint = { x: e.clientX, y: e.clientY }; dragContainer.onmousemove = e => { //鼠标滑动的实时距离 let dragMoveDiff = { x: mouseDownPoint.x - e.clientX, y: mouseDownPoint.y - e.clientY }; scrollContainer.scrollLeft = mouseDownScrollPosition.scrollLeft + dragMoveDiff.x; scrollContainer.scrollTop = mouseDownScrollPosition.scrollTop + dragMoveDiff.y; }; document.onmouseup = e => { dragContainer.onmousemove = null; document.onmouseup = null; }; }; </script> </html>
关联文章