簡體   English   中英

放大或縮小 HTML 滾動元素

[英]Zoom-in or Zoom-out HTML Element on Scroll

我有一個浮動的img ,用戶可以按下鼠標左鍵移動; 但我也想在用戶嘗試滾動圖像時放大和縮小圖像。

我找不到像onscrollforewardonscrollbackward的適當事件。

/* Here I want to zoom-in an image.
*/ image.onscrollforeward = function( e ) { ... };

/* And here to zoom-out.
*/ image.onscrollbackward = function( e ) { ... };

我沒有完全理解你的問題,但我知道一種方法來檢測用戶是向上還是向下滾動。

也許這個片段可以幫助你。

 window.onscroll = function(e) { // print "false" if direction is down and "true" if up console.log(this.oldScroll > this.scrollY); this.oldScroll = this.scrollY; }
 .container { position: relative; background: #ccc; width: 500px; height: 1500px; padding: 15px; } img { position: fixed; }
 <div class="container"> <img src="https://placekitten.com/200/200" alt="pixelkitten"> </div>

編輯我已經稍微改變了 javascript,現在應該可以幫助你了。

const image = document.querySelector('img');

image.onscrollforeward = function( e ) { ... };

image.onscrollbackward = function( e ) { ... };    

image.onwheel = function _image__onwheel( e ) {
    e.preventDefault();
    if (e.deltaY < 0) this.onscrollforeward( e );
    else this.onscrollbackward( e );
};

這是我將用於我的案例的確切代碼:

const image = document.getElementById('floatingImage');

image.zoom = 1;

image.onwheel = function _image__onwheel( event ) {
    event.preventDefault();
    this[ e.deltaY < 0 ? 'onscrollforeward' : 'onscrollbackward' ]();
};

image.onscrollforeward = function _image__onscrollforeward( ) {
    this.style.transform = `scale(${ ++this.zoom })`;
};

image.onscrollbackward = function _image__onscrollbackward( ) {
    this.style.transform = `scale(${ --this.zoom })`;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM