滚动时放大或缩小HTML元素



我有一个浮动的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>

EDIT我对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 })`;
};

最新更新