angular2以上自定义指令 放大镜效果预览图片

效果依赖jquery,需提前安装

  1. 创建指令文件my-preview.directive.ts
    import { Directive, Input, Output, EventEmitter, HostListener, OnInit, OnDestroy,ElementRef,Renderer2 } from '@angular/core';
    //
    import * as $ from 'jquery';
    @Directive({
    selector: '[myPreview]'
    })
    export class MyPreviewDirective {
    @Input('maxSize') size: number = 300;//放大镜的长和宽
    @Input('hoverToggle') toggle: boolean = true; //悬浮图片开关
    constructor(
        private ele: ElementRef,
        private render: Renderer2,
    ) { 
        this.render.setStyle(this.ele.nativeElement, 'cursor', 'pointer');
    }
    //鼠标移入图片
    @HostListener('mouseover', ['$event'])
    showImg(el: MouseEvent){
        if (this.toggle !== true) {
        return;
        }
        if (el.target['src'].includes('error')) {
        return;
        }
        //先清除后添加
        $('#max').remove() 
        //el.target['src']此处使用的是目标对象的图片地址,也可自定义传入大图地址,替换变量
        let $maxImg = `<div id="max" style="display:none;position:fixed;z-index:9999; width:${this.size}px; height:${this.size}px; background-image:url(${el.target['src']})"></div>`;
        $('body').append($maxImg);
    }
    //鼠标图片上移到
    @HostListener('mousemove', ['$event'])
    moveImg(el: MouseEvent) {
        if (this.toggle !== true) {
        return;
        }
        if (el.target['src'].includes('error')) {
        return;
        }
        //获取鼠标所在图片位置坐标占图片长宽的比例
        let positionX=(el.offsetX/el.target['width'])*100
        let positionY=(el.offsetY/el.target['height'])*100
        // console.log(positionX,positionY)
        //设置放大背景图片的背景位移 
        $('#max').css('backgroundPositionX', (positionX<0?0:positionX>100?100:positionX)+'%').css('backgroundPositionY',(positionY<0?0:positionY>100?100:positionY)+'%');
        //同坐左右侧判断放大镜展示左右位置
        if(positionX>50){
        $('#max').css(  'left', el.clientX-this.size-20)
        }else{
        $('#max').css(  'left', el.clientX+20)
        }
        if(positionY>50){
        $('#max').css('top', el.clientY-this.size-20)
        }else{
        $('#max').css('top', el.clientY+20)
        }
        $('#max').show();
        
    }
    //鼠标移出图片
    @HostListener('mouseout', ['$event'])
    hideImg(el: MouseEvent) {
        if (this.toggle !== true) {
        return;
        }
        $('#max').remove();
    }

    }

  1. 接下来就可以将它应用到组件中 app.module.ts
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserModule } from '@angular/platform-browser';
import { MyPreviewDirective } from './my-preview.directive';

@NgModule({
declarations: [
    AppComponent,
    MyPreviewDirective
],
imports: [
    BrowserModule
],

providers: [ ],

bootstrap: [AppComponent]
})
export class AppModule { }

  1. 在标签中使用

<img [src]="图片地址"  imgDetail >

jQuery中放大镜预览图片


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <!-- http:localhost/1.jpg图片地址 -->
    <img src="http:localhost/1.jpg" alt="" class="myImg">
    <script>
        $("body").on("mouseover", ".myImg", function(el) {
                  //先清除后添加
          
            $('#max').remove() 
            let $maxImg = `<div id="max" style="display:none;position:fixed;z-index:9999; width:300px; height:300px; background-image:url(${el.target['src']})"></div>`;
            $('body').append($maxImg);
    });
        $("body").on("mousemove", ".myImg", function(el) {
            //获取鼠标所在图片位置坐标占图片长宽的比例
            let positionX=(el.offsetX/el.target['width'])*100
            let positionY=(el.offsetY/el.target['height'])*100
            //设置放大背景图片的背景位移 左右两端给10%的距离防止卷边影响
            $('#max').css('backgroundPositionX', (positionX<0?0:positionX>100?100:positionX)+'%').css('backgroundPositionY',(positionY<0?0:positionY>100?100:positionY)+'%');
            //同坐左右侧判断放大镜展示左右位置--如果只是单张图可判断positionX
            if(positionX>50){
                console.log(el.clientX-300-20)
            $('#max').css(  'left', el.clientX-300-20)
            }else{
            $('#max').css(  'left', el.clientX+20)
            }
            if(positionY>50){
            $('#max').css('top', el.clientY-300-20)
            }else{
            $('#max').css('top', el.clientY+20)
            }
            $('#max').show();
    });
        $("body").on("mouseout", ".myImg", function() {
            $('#max').remove();
    });
    </script>
</body>
</html>