LoginSignup
2
2

More than 1 year has passed since last update.

jQueryとCSSでマウスカーソルを良い感じに

Last updated at Posted at 2021-01-11

最近ちょくちょく見かけるマウスカーソル
2つの円形を作って、1つは通常のカーソルの動き、2つは少し遅らせ追従するような動きになるように作りました。

画面収録-2021-01-11-14.38.gif

HTML

dot1とdot2で大きい円と小さい円

html
<div class="cursor">
  <span class="dot1"></span>
  <span class="dot2"></span>
</div>

jQuery

  • $(window).mousemoveでカーソルのホットスポットが要素内(body)で動いた時の処理
  • left: e.pageX , top: e.pageYで座標を取得
  • $('a').on('mouseenter', function () { } でaタグにホバーしたときにactiveというクラスを追加
jquery
$(window).mousemove(function (e) {
  $('.cursor span').css({
    left: e.pageX,
    top: e.pageY
  })
})
$('a').on('mouseenter', function () {
  $('.cursor span').addClass('active');
})
$('a').on('mouseleave', function () {
  $('.cursor span').removeClass('active');
})

CSS

  • cursor: none;でデフォルトのカーソルを非表示
  • .cursor span { } の中で基本的な形(今回だと円形)を作る
  • dot1とdot2にそれぞれの形を作る
  • .activeでホバー時の形を作る
css
* {
  cursor: none;
}
.cursor span {
  height: 10px;
  width: 10px;
  border-radius: 100%;
  transform: translate(-50%, -50%);
  position: absolute;
  z-index: 1;
  pointer-events: none;
}
.cursor span.dot1 {
  background: rgba(98, 77, 112, 0.8);
  transition: width 0.2s, height 0.2s;
}
.cursor span.dot1.active {
  height: 50px;
  width: 50px;
  background: rgba(98, 77, 112, 0.3);
}
.cursor span.dot2 {
  height: 20px;
  width: 20px;
  border: solid 1px #624d70;
  transition: top 0.2s, left 0.2s, width 0.5s, height 0.5s;
  transition-timing-function: ease-out;
}
.cursor span.dot2.active {
  height: 80px;
  width: 80px;
}

2つ目の円形の動きの遅延

円形の1つの動きを transition: top 0.2s, left 0.2s, width 0.5s, height 0.5s; で少し遅らせて、後を追うような動きにしています。

  • 追従の遅延は top 0.2s, left 0.2s
  • 大きさの遅延は width 0.5s, height 0.5s

それぞれの数字を変えると動きを変えることができます。

transitionについて詳しくは以下
https://developer.mozilla.org/ja/docs/Web/CSS/transition

ipadのようにテキスト部分にホバーすると縦棒になるようにカスタマイズ

gif.gif

CSSとjQueryに以下を追加

css
.cursor span.dot1.text_active {
  height: 1.4em;
  width: 2px;
  border-radius: 0;
}
.cursor span.dot2.text_active {
  display: none;
}
jquery
$('p').on('mouseenter', function () {
  $('.cursor span').addClass('text_active');
})
$('p').on('mouseleave', function () {
  $('.cursor span').removeClass('text_active');
})
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2