实现左右盒子由中间按钮拖动

   dragdrop(){
    const dragBar = document.getElementById('dragBar');
        const leftBox = document.querySelector('.left');
        const rightBox = document.querySelector('.right');

        let isDragging = false;
        let startX = 0;
        let leftWidth = 0;
        let rightWidth = 0;
        dragBar.addEventListener('mousedown', (e) => {
            isDragging = true;
            startX = e.clientX;
            leftWidth = leftBox.offsetWidth;
            rightWidth = rightBox.offsetWidth;
            
            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });

        function onMouseMove(e) {
            if (!isDragging) return;
            
            const deltaX = e.clientX - startX;
            const newLeftWidth = leftWidth + deltaX;
            const newRightWidth = rightWidth - deltaX;

            // 边界检查
            if (newLeftWidth < 280) {
                leftBox.style.width = '280px';
                rightBox.style.width = `${rightWidth + (leftWidth - 280)}px`;
                return;
            }
            
            if (newRightWidth < 200) {
                leftBox.style.width = `${1138}px`;
                rightBox.style.width = '200px';
                return;
            }

            leftBox.style.width = `${Math.round(newLeftWidth)}px`;
            rightBox.style.width = `${Math.round(newRightWidth)}px`;
        }

        function onMouseUp() {
            isDragging = false;
            document.removeEventListener('mousemove', onMouseMove);
            document.removeEventListener('mouseup', onMouseUp);
        }

   },

你可能感兴趣的:(javascript,前端,开发语言)