Div跟随鼠标悬停指针

时间:2019-04-18 03:25:03

标签: javascript jquery css hover

当您将鼠标悬停在某些div上时,我想显示一个跟随指针的浮动div,到目前为止,我发现这段带有jQuery的代码在悬停整个主体时都有效,但是我想要的是在某些div上工作:

CSS

<div id="tail">mouse tail</div>

jQuery

$(document).bind('mousemove', function(e){
    $('#tail').css({
       left:  e.pageX + 20,
       top:   e.pageY
    });
});

我尝试了bind到特定的选择器,但是没有用。

当您将鼠标悬停在div之外时,div应该消失;当您悬停在div上时,div应该重新出现。

2 个答案:

答案 0 :(得分:5)

只需在鼠标离开时将div显示设置为无,在鼠标进入时将显示块设置为

$('.something').bind('mousemove', function(e){
    $('#tail').css({
       left:  e.pageX + 20,
       top:   e.pageY
    });
});

$('.something').bind('mouseleave', function(e){
    $('#tail').css({
       display:  'none'
    });
});
$('.something').bind('mouseenter', function(e){
    $('#tail').css({
       display:  'block'
    });
});
#tail {
  position: fixed;
  display: none;
}

.something {
  width: 200px;
  height: 160px;
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tail">mouse tail</div>

<div class='something'> stuff </div>

答案 1 :(得分:1)

定位特定的div,为它们分配onmouseenter / onmouseleave事件:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate {

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    print("Cell \(indexPath.row)")
    cell.contentView.backgroundColor = .orange
    return cell
}
//MARK: scrollview Delegate Method
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    print("scrollViewWillEndDragging is called")
}

#tail {
  position: fixed;
}

.hidden {
  display: none;
};