萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 圖片縮放滑桿:原生 JS 實現拖曳控制圖片大小

功能展示

  • 滑桿拖曳控制圖片縮放比例(0%~200%)
  • 左右箭頭按鈕微調
  • 即時顯示縮放百分比
  • 保持圖片原始長寬比

完整實作代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>拖動條改變圖片大小</title>
    <style>
        * { margin: 0; padding: 0; font-size: 12px; }
        .btn { width: 50px; height: 15px; cursor: pointer; }
        
        #picViewPanel {
            margin: 5px 50px 0;
            width: 278px; height: 200px;
            overflow: auto; text-align: center;
            border: 1px solid #ccc;
        }
        
        #slider {
            margin: 0 50px; height: 15px; width: 278px;
            border: 1px solid #000; position: relative;
        }
        
        #sliderLeft, #sliderRight {
            height: 13px; width: 13px; border: 1px solid #ccc;
            cursor: pointer; float: left;
        }
        #sliderRight { float: right; }
        
        #sliderBlock {
            height: 13px; width: 50px; border: 1px solid #ccc;
            position: absolute; top: 0; left: 113px;
            background: #ccc; cursor: pointer;
            text-align: center; line-height: 13px;
            user-select: none;
        }
    </style>
</head>
<body>
    <div id="picViewPanel"></div>
    <div id="slider">
        <span id="sliderLeft"><<</span>
        <span id="sliderRight">>></span>
        <span id="sliderBlock">==</span>
    </div>

    <script>
        // 圖片檢視類
        class PicView {
            constructor(url, alt = '') {
                this.url = url;
                this.alt = alt;
                this.zoom = 1;
                this.realWidth = 0;
                this.realHeight = 0;
                this.init();
            }
            
            init() {
                this.obj = document.createElement('img');
                this.obj.src = this.url;
                this.obj.alt = this.alt;
                this.obj.style.zoom = this.zoom;
                document.getElementById('picViewPanel').appendChild(this.obj);
                
                // 等待圖片載入後取得原始尺寸
                this.obj.onload = () => {
                    this.realWidth = this.obj.offsetWidth;
                    this.realHeight = this.obj.offsetHeight;
                };
            }
            
            reBind() {
                this.obj.style.width = this.realWidth * this.zoom + 'px';
                this.obj.style.height = this.realHeight * this.zoom + 'px';
            }
            
            setZoom(ratio) {
                this.zoom = ratio;
                this.reBind();
            }
        }

        // 滑桿控制類
        class Slider {
            constructor(onChange, onEnd) {
                this.block = document.getElementById('sliderBlock');
                this.percent = 50; // 初始 50% = 100% 顯示
                this.value = 0;
                this.onChange = onChange;
                this.onEnd = onEnd;
                this.dragging = false;
                this.init();
            }
            
            init() {
                const block = this.block;
                const slider = document.getElementById('slider');
                const leftBtn = document.getElementById('sliderLeft');
                const rightBtn = document.getElementById('sliderRight');
                const minLeft = 13; // 左按鈕寬度
                const maxLeft = slider.offsetWidth - block.offsetWidth - 13; // 右邊界
                
                // 拖曳邏輯
                block.addEventListener('mousedown', e => {
                    this.dragging = true;
                    this.startX = e.clientX - block.offsetLeft;
                    document.body.style.userSelect = 'none';
                });
                
                document.addEventListener('mousemove', e => {
                    if (!this.dragging) return;
                    let posX = e.clientX - this.startX;
                    posX = Math.max(minLeft, Math.min(maxLeft, posX));
                    block.style.left = posX + 'px';
                    
                    this.percent = (posX - minLeft) / 2; // 0-100 對應 0-200%
                    this.onChange(this.percent);
                });
                
                document.addEventListener('mouseup', () => {
                    if (this.dragging) {
                        this.dragging = false;
                        document.body.style.userSelect = '';
                        this.onEnd?.();
                    }
                });
                
                // 箭頭按鈕點擊微調
                leftBtn.addEventListener('click', () => this.adjust(-1));
                rightBtn.addEventListener('click', () => this.adjust(1));
            }
            
            adjust(delta) {
                const newPercent = Math.max(0, Math.min(100, this.percent + delta));
                this.percent = newPercent;
                const minLeft = 13;
                this.block.style.left = (minLeft + newPercent * 2) + 'px';
                this.onChange(newPercent);
            }
        }

        // 初始化
        window.addEventListener('load', () => {
            const pv = new PicView('/images/logo.gif');
            const sd = new Slider(
                p => {
                    document.getElementById('sliderBlock').innerHTML = (2 * p) + '%';
                    pv.setZoom(2 * p / 100);
                },
                () => {}
            );
        });
    </script>
</body>
</html>

核心邏輯詳解

PicView 類:圖片載入與縮放

  • 動態建立 <img> 元素並加入容器
  • onload 確保取得真實原始尺寸(避免 CSS 影響)
  • setZoom() 透過設定 width/height 實現縮放,保持比例
  • 原版使用 style.zoom 為 IE 專屬屬性,現代改用尺寸縮放

Slider 類:拖曳與互動

  • 滑塊活動範圍:左邊界 13px(左按鈕寬度)~ 右邊界 248px
  • mousedown/mousemove/mouseup 事件鏈實現拖曳
  • user-select: none 防止拖曳時選取文字
  • 百分比映射:0~100 對應 0%~200% 縮放比
  • 箭頭按鈕提供無障礙微調入口

現代化改良:使用 <input type="range">

<!-- HTML -->
<div class="image-zoom">
    <div class="preview"><img id="targetImg" src="/images/logo.gif" alt=""></div>
    <div class="controls">
        <button id="zoomOut" aria-label="縮小">−</button>
        <input type="range" id="zoomRange" min="10" max="300" value="100" step="5">
        <output id="zoomValue">100%</output>
        <button id="zoomIn" aria-label="放大">+</button>
        <button id="resetZoom">重置</button>
    </div>
</div>

<style>
.image-zoom { max-width: 400px; margin: 2rem auto; font-family: system-ui; }
.preview { overflow: auto; text-align: center; border: 1px solid #ddd; border-radius: 4px; }
.preview img { transition: transform 0.1s ease; transform-origin: center top; }
.controls { display: flex; align-items: center; gap: 8px; margin-top: 12px; padding: 0 8px; }
.controls input[type="range"] { flex: 1; }
.controls output { min-width: 45px; text-align: right; font-variant-numeric: tabular-nums; }
.controls button { padding: 4px 10px; border: 1px solid #ccc; background: #f5f5f5; border-radius: 3px; cursor: pointer; }
.controls button:hover { background: #eee; }
</style>

<script>
const img = document.getElementById('targetImg');
const range = document.getElementById('zoomRange');
const output = document.getElementById('zoomValue');

function applyZoom(val) {
    const ratio = val / 100;
    img.style.transform = `scale(${ratio})`;
    output.textContent = val + '%';
}

range.addEventListener('input', e => applyZoom(+e.target.value));
document.getElementById('zoomOut').addEventListener('click', () => {
    range.value = Math.max(10, +range.value - 5);
    range.dispatchEvent(new Event('input'));
});
document.getElementById('zoomIn').addEventListener('click', () => {
    range.value = Math.min(300, +range.value + 5);
    range.dispatchEvent(new Event('input'));
});
document.getElementById('resetZoom').addEventListener('click', () => {
    range.value = 100;
    range.dispatchEvent(new Event('input'));
});

// 初始化
applyZoom(100);
</script>

原生 range 優勢

  • 零依賴、原生無障礙(鍵盤操作、螢幕閱讀器支援)
  • 觸控裝置原生支援滑動
  • 瀏覽器內建 UI,無需手寫拖曳邏輯
  • 可用 CSS 自訂外觀(::-webkit-slider-thumb 等偽元素)

進階功能擴充

  • 雙向同步:滾輪縮放時同步更新滑桿
  • 拖曳移動:縮放後可拖曳檢視區域(transform-origin + translate)
  • 雙擊重置:雙擊圖片恢復 100%
  • 鍵盤快捷鍵:+/- 縮放,0 重置
copyright © 萬盛學電腦網 all rights reserved