【问题标题】:Zoom-in or Zoom-out HTML Element on Scroll滚动时放大或缩小 HTML 元素
【发布时间】:2023-03-03 11:22:01
【问题描述】:

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

我找不到像 onscrollforewardonscrollbackward 这样的合适事件。

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

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

【问题讨论】:

  • @Rishab 首先,我无法打开您的链接,这对我来说只是一个空白页面。第二:我不想使用臃肿的 jQuery 或类似的东西。

标签: javascript html dom scroll dom-events


【解决方案1】:

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

也许这个 sn-p 可以帮助你。

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

【讨论】:

  • 对不起,但是当我在 img 元素上分配 onscroll 时,这不起作用。我到底想得到什么:2ch.hk/b (18+);只需单击此站点上的任何图像并尝试滚动即可。
  • 我什至尝试在我的图像元素上设置overflow: scroll - 结果是一样的。
  • 在这种情况下,您希望根据用户输入滚动放大图像。我的回答确实检查了滚动用户输入。我会编辑我的答案给我 5 分钟
  • 仍然不起作用:它只是滚动我的页面,我没有得到控制台的输出。 :(
  • 而且这不仅仅在 Firefox 中有效。它在 Chromium 中运行良好。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2015-06-09
    • 2023-04-01
    • 2014-05-23
    • 1970-01-01
    相关资源
    最近更新 更多