滚动上的放大或缩小HTML元素

问题描述 投票:0回答:2

我有一个浮动的img,用户可以通过按下鼠标左键来移动它;但我也想在用户尝试滚动时放大和缩小图像。

我找不到适合的事件,例如onscrollforewardonscrollbackward

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

/* And here to zoom-out.
*/ image.onscrollbackward = function( e ) { ... };
javascript html dom scroll dom-events
2个回答
1
投票

我不完全理解您的问题,但是我知道一种检测用户是向上还是向下滚动的方法。

也许此代码段可以帮助您。

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 );
};

0
投票

这是我将用于案例的确切代码:

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 })`;
};
© www.soinside.com 2019 - 2024. All rights reserved.