You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需jQuery在Angular 17可滚动容器中实现双击滚动功能

在Angular 17中实现编辑器容器的双击滚动功能

可以通过Angular的事件绑定和原生DOM操作实现双击滚动,无需依赖jQuery。以下是具体实现方案:

步骤1:修改模板,添加事件绑定和模板引用

给滚动容器添加模板引用变量,并绑定双击事件:

<div class="outer">
  <div class="editor-container-outer" #scrollContainer (dblclick)="handleDoubleClick($event, scrollContainer)">
    <div class="editor-container">
      My editor components
    </div>
  </div>
</div>

步骤2:组件类中实现滚动逻辑

在组件的TypeScript代码中编写双击事件处理函数,根据点击位置控制滚动方向和距离:

import { Component } from '@angular/core';

@Component({
  selector: 'app-your-component', // 替换为你的组件选择器
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  // 自定义滚动步长(容器视口的比例)
  private scrollRatio = 0.8;

  handleDoubleClick(event: MouseEvent, scrollContainer: HTMLElement): void {
    const rect = scrollContainer.getBoundingClientRect();
    const containerHeight = rect.height;
    const containerWidth = rect.width;

    // 计算点击位置相对于容器的坐标
    const relativeY = event.clientY - rect.top;
    const relativeX = event.clientX - rect.left;

    // 垂直滚动:点击上半部分向上滚,下半部分向下滚
    if (relativeY < containerHeight / 2) {
      scrollContainer.scrollTop -= containerHeight * this.scrollRatio;
    } else {
      scrollContainer.scrollTop += containerHeight * this.scrollRatio;
    }

    // 可选:水平滚动逻辑,点击左半部分向左滚,右半部分向右滚
    if (relativeX < containerWidth / 2) {
      scrollContainer.scrollLeft -= containerWidth * this.scrollRatio;
    } else {
      scrollContainer.scrollLeft += containerWidth * this.scrollRatio;
    }
  }
}

步骤3:优化滚动体验(可选)

给滚动容器添加平滑滚动效果,修改CSS:

.editor-container-outer {
  width: 100%;
  height: 100%;
  overflow: scroll;
  scroll-behavior: smooth; /* 开启平滑滚动动画 */
}

/* 保留你原有的其他CSS */
.outer {
  width: 700px;
  height: 400px;
  border: 1px solid black;
}

.editor-container {
  background-color: aqua;
  width: 2000px;
  height: 1500px;
  overflow: auto;
  cursor: pointer;
}
::-webkit-scrollbar {
  display: none;
}

说明

  • 模板引用变量#scrollContainer用于直接获取DOM元素,避免使用document.querySelector,符合Angular的最佳实践。
  • 滚动步长scrollRatio可根据需求调整,比如设为1时每次滚动整个视口高度/宽度。
  • 平滑滚动依赖scroll-behavior: smooth,现代浏览器均支持该属性。

内容的提问来源于stack exchange,提问作者Thiru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:15:19