찾다
웹 프론트엔드JS 튜토리얼jQuery: mouseenter 이벤트 및 mouseleave 이벤트로 인해 깜박임 문제가 발생함

안녕하세요 여러분. 오늘은 이미지 돋보기용 jquery 플러그인을 만들고 있습니다. JD.com의 상품사진 돋보기와 비슷합니다.

mouseenter와 mouseleave를 이미지 객체에 바인딩한 후 마우스가 이미지 위에서 움직일 때 mouseenter와 mouseleave가 동시에 실행되어 깜박임을 유발하는 것을 발견했습니다. 그러나 나는 mouseenter와 mouseleave가 동시에 반복적으로 호출될 것이라고 기대하지 않습니다. 어떻게 해결하나요? 온라인에서 여러 가지 방법을 시도했지만 아무 소용이 없었습니다.

모두 감사합니다.

$.fn.magnify = function() {
    //var glassBox = options.glassBox || {};
    //var detailBox = options.detailBox || {};

    var glassBox = $(&#39;<span></span>&#39;);

    glassBox.css({
        "width": this.width() / 2 + &#39;px&#39;,
        "height": this.height() /2 + &#39;px&#39;,
        "background-color": &#39;grey&#39;,
        "position": "absolute",
        "left" : &#39;0px&#39;,
        "top": &#39;0px&#39;,
        &#39;opacity&#39;: &#39;0.2&#39;,
        &#39;display&#39;: &#39;none&#39;,
        &#39;border&#39;: &#39;1px solid blue&#39;,
        &#39;z-index&#39;: 10

    });

    $(this).after(glassBox);
    //glassBox.hide();

    var detailBox = $(&#39;<div></div>&#39;);
    var detailImage = $(&#39;<img  src="/static/imghwm/default1.png"  data-src="jquery-1.11.3.js"  class="lazy"  alt="jQuery: mouseenter 이벤트 및 mouseleave 이벤트로 인해 깜박임 문제가 발생함" ></img>&#39;);
    
    detailBox.css({
        "width": this.width(),
        "height": this.height(),
        "display": &#39;none&#39;,
        "position": &#39;relative&#39;,
        "overflow": &#39;hidden&#39;
        //"background-color": &#39;lime&#39;
    });
    detailImage.css({
        "position": &#39;absolute&#39;
    });
    detailImage.attr("src", this.attr("src"));
    detailBox.append(detailImage);
    this.after(detailBox);


    this.mouseenter(function(event){
        //event.stopPropagation();
        glassBox.get(0).style.display = &#39;block&#39;;
        detailBox.get(0).style.display = &#39;block&#39;;
        
        

    });
    this.mouseleave(function(event){    
        //event.stopPropagation();
        if (event.relatedTarget !== "span") {
            glassBox.get(0).style.display = &#39;none&#39;;
        detailBox.get(0).style.display = &#39;none&#39;;
        }
        
    });

    this.mousemove(function(event) {
        /* Act on the event */
        var x = event.pageX - this.offsetLeft - glassBox.width() / 2;
        var y = event.pageY - this.offsetTop - glassBox.height() /2;
        if (x < 0 ) {
            x = 0;
        } else if ( x > this.offsetWidth - glassBox.width()) {
            x = this.offsetWidth - glassBox.width();
        }
        if (y < 0) {
            y = 0;
        } else if (y > this.offsetHeight - glassBox.height()) {
            y = this.offsetHeight - glassBox.height();
        }
        glassBox.css({
            left: x + &#39;px&#39;,
            top:  y + &#39;px&#39;
        });

        detailImage.css({
        "left": -3.5 * (event.pageX - this.offsetLeft) + &#39;px&#39;,
        "top": -3.5 * (event.pageY - this.offsetTop) + &#39;px&#39;
    });
    });
}

HTML은 다음과 같습니다.

<html>
    <head>
        <script ></script>
        <script src="magnify.js"></script>
    </head>
    <style>
        #imgTarget{
            width: 300px;
            height: 200px;
        }
        #imageArea{
            position: relative;
        }
    </style>
    <body>
        <div id="imageArea">
            <img  src="/static/imghwm/default1.png"  data-src="car.jpg"  class="lazy"  id="imgTarget" / alt="jQuery: mouseenter 이벤트 및 mouseleave 이벤트로 인해 깜박임 문제가 발생함" >
        </div>

        <script>
            $( document ).ready( function(){
                $("#imgTarget").magnify();
            } );

        </script>


    </body>


</html>

깜박이는 이유는 다음과 같습니다.

mouseenter mouseleave 이벤트를 img에 바인딩했습니다.

mouseenter img를 실행하면 img의 상위 레이어에 glassBox

glassBox가 생성되었으므로 img와 마우스 커서를 차단하면 img에 대한 mouseleave가 생성됩니다

그래서 코드는 glassBox display=none을 다시 설정하고 마우스는 img에 다시 들어갈 수 있습니다

해결책 1
mouseenter mouseleave를 사용하는 대신 mousemove에서 직접 여부를 결정합니다. 마우스 위치가 img 범위 내에 있습니다.

해결책 2
img와 동일한 크기의 오버레이 만들기:

<div id="imageArea">
 <img  src="/static/imghwm/default1.png"  data-src="card.jpg"  class="lazy"  id="imgTarget" / alt="jQuery: mouseenter 이벤트 및 mouseleave 이벤트로 인해 깜박임 문제가 발생함" >
 <div id="overlay"></div>
</div>
#overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  height: 200px;
  background: red;
  opacity: 0.5;
  z-index: 3;
}

img glassBox 오버레이의 Z-색인 순서 보장:

glassBox.css({
        "width": this.width() / 2 + &#39;px&#39;,
        "height": this.height() /2 + &#39;px&#39;,
        "background-color": &#39;grey&#39;,
        "position": "absolute",
        "left" : &#39;0px&#39;,
        "top": &#39;0px&#39;,
        &#39;opacity&#39;: &#39;0.2&#39;,
        &#39;display&#39;: &#39;none&#39;,
        &#39;border&#39;: &#39;1px solid blue&#39;,
        &#39;z-index&#39;: 2 // 保证glassBox在overlay的下面,在img的上面
    });

이벤트는 오버레이에 바인딩됩니다:

$( document ).ready( function(){
    $("#overlay").magnify(); 
} );

위 내용은 jQuery: mouseenter 이벤트 및 mouseleave 이벤트로 인해 깜박임 문제가 발생함의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는