angular2以上自定义指令 放大镜效果预览图片
效果依赖jquery,需提前安装
- 创建指令文件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();
}
}
- 接下来就可以将它应用到组件中 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 { }
- 在标签中使用
<img [src]="图片地址" imgDetail >
标签:el,return,自定义,预览,max,angular2,import,css,图片
From: https://www.cnblogs.com/ly96/p/17140886.html