2017-10-26 4 views
0

div .drag-indicatorにカーソルを追従させたいと思います。クリックすると消えます。以下のコードはこれを実現していますが、特定のdivにホバーするときにのみこの動作が発生するようにしてください。.carousel現在のコードでは、画面上の位置に関係なく、またそのdiv内だけでなくクリックが行われたときにも、.drag-indicatorがマウスに追従します。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

グレート、ありがとうロリー!うまくいけば、.carousel上にホバリングしないと.drag-indicatorを非表示にすることは可能でしょうか?現時点で、ホバーが終了すると、ドラッグインジケータは最後の既知の位置にとどまります。おかげで –

+0

確かに、あなたはそれを行うためにCSSを使用することができます。私はあなたの答えを更新しました –

+0

ありがとう、私は.fadeOut関数に問題があります、それはもはや私のために働いていますが、うまくいけばあなたの例で見ることができます。何か案は?また、マウスを動かすとかなりちらつきが増えています。 –

関連する問題