2017-10-26 7 views
0

div .drag-indicator이 커서를 따라 가고 싶으면 클릭이 발생하면 사라집니다. 아래 코드는 이것을 달성하지만 특정 div .carousel 위로 마우스를 가져 가면이 동작이 발생하기를 원합니다. 현재 코드는 화면의 위치와 상관없이 .drag- 표시기를 마우스로 이동시킵니다.Div는 특정 부모 내에서만 커서를 따라갑니다

내 코드가 다소 간소화 될 수 있으므로 여기에 조언이 있으면 좋을 것입니다. 나는 그것을 단지 하나의 기능으로 만들고 싶다.

감사합니다.

/* Follow cursor */ 
 
$(document).on('mousemove', function(e) { 
 
    $('.drag-indicator').css({ 
 
    left: e.pageX, 
 
    top: e.pageY 
 
    }); 
 
}); 
 

 
/* Hide when clicked */ 
 
$(document).on('mousedown', function(e) { 
 
    $('.drag-indicator').fadeOut(300) 
 
});
.drag-indicator { 
 
    position: absolute; 
 
    width: 50px; 
 
    height: 50px; 
 
    border-radius: 100%; 
 
    background-color: red; 
 
    z-index: 9999; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="carousel"> 
 
    <div class="carousel-cell">CELL CONTENT</div> 
 
    <div class="carousel-cell">CELL CONTENT</div> 
 
    <div class="carousel-cell">CELL CONTENT</div> 
 
    <div class="drag-indicator">DRAG INDICATOR</div> 
 
</div>

답변

1

당신이 필요한만큼,이 작품을 만드는 document 대신 .carousel에 직접 이벤트 핸들러를 연결하려면 :

$('.carousel').on({ 
 
    mousemove: function(e) { 
 
    $('.drag-indicator').css({ 
 
     left: e.pageX, 
 
     top: e.pageY 
 
    }) 
 
    }, 
 
    mousedown: function(e) { 
 
    $('.drag-indicator').fadeOut(300) 
 
    } 
 
});
.drag-indicator { 
 
    position: absolute; 
 
    width: 50px; 
 
    height: 50px; 
 
    border-radius: 100%; 
 
    background-color: red; 
 
    z-index: 9999; 
 
} 
 

 
.carousel { 
 
    border: 1px solid #C00; 
 
} 
 

 
.carousel .drag-indicator { 
 
    display: none; 
 
} 
 
.carousel:hover .drag-indicator { 
 
    display: block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="carousel"> 
 
    <div class="carousel-cell">CELL CONTENT</div> 
 
    <div class="carousel-cell">CELL CONTENT</div> 
 
    <div class="carousel-cell">CELL CONTENT</div> 
 
    <div class="drag-indicator">DRAG INDICATOR</div> 
 
</div>

+0

좋아요, 감사 로리! 그래도 잘 작동하지만 .drag-indicator를 .carousel 위에 올려 놓지 않을 때 숨길 수 있습니까? 현재, 호버가 끝나면 드래그 표시기는 마지막으로 알려진 위치에 남아 있습니다. 고마워요. –

+0

예, CSS를 사용하면 그렇게 할 수 있습니다. –

+0

감사합니다. Rory, .fadeOut 함수에 문제가 있습니다. 더 이상 작동하지 않지만 잘 작동하는 예제에서 볼 수 있습니다. 어떤 아이디어? 또한 마우스를 움직일 때 깜박임이 꽤 많이 생깁니 까? –