こんにちわ。
米田です。
今回はマウスストーカなるものをご紹介します。
読んで字のごとく、マウスポインターに追従するアニメーションのことです。
マウスポインターにまでこだわりたい!
という方はぜひ参考にしてみてください。
目次/このページでわかること
完成形
See the Pen mavpjb by epauoh (@epauoh) on CodePen.dark
マウスポインター自体が白い点になり、半透明の円が追従してきます。
hover時はマウスポインターが消え、半透明の円が大きくなります。
※もちろんスマホにはマウスポインターはありません。pcで確認してください。
実装
今回はプラグインを使用しないので、jQueryを読み込むだけでokです。 HTMLも特に必要な記述はありません。 今回はhover要素のみおいています。
CSS
a要素にhover時、activeのクラスが付与されるので、 hover時に必要なアクションはそこで指定してください。
#cursor { position: fixed; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); background: #fff; width: 5px; height: 5px; border-radius: 100%; pointer-events: none; } #cursor.active { transform: scale(0); } #stalker { position: fixed; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); background: #fff; width: 40px; height: 40px; border-radius: 100%; transition: 0.2s; opacity: .3; pointer-events: none; } #stalker.active { transform: scale(3); }
JS
1.if文でpcでのみ実行するようにします。
if(!navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/))
2.body内にdiv要素を2つ生成し、idを付与します。
var body = document.body;
var cursor = document.createElement("div");
var stalker = document.createElement("div");
cursor.id = "cursor";
stalker.id = "stalker";
body.appendChild(cursor);
body.appendChild(stalker);
3.マウスポインターの位置を取得し、指定します。
body.addEventListener("mousemove", function(e) {
cursor.style.left = e.clientX + "px";
cursor.style.top = e.clientY + "px";
stalker.style.left = e.clientX + "px";
stalker.style.top = e.clientY + "px";
}, false);
4.a要素にhover時、activeのクラスを付与します。
$("a").on("mouseenter", function() {
$('#cursor').addClass("active");
$('#stalker').addClass("active");
});
$("a").on("mouseleave", function() {
$('#cursor').removeClass("active");
$('#stalker').removeClass("active");
});
全体
if(!navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/)){
$(function(){
var body = document.body;
var cursor = document.createElement("div");
var stalker = document.createElement("div");
cursor.id = "cursor";
stalker.id = "stalker";
body.appendChild(cursor);
body.appendChild(stalker);
body.addEventListener("mousemove", function(e) {
cursor.style.left = e.clientX + "px";
cursor.style.top = e.clientY + "px";
stalker.style.left = e.clientX + "px";
stalker.style.top = e.clientY + "px";
}, false);
$("a").on("mouseenter", function() {
$('#cursor').addClass("active");
$('#stalker').addClass("active");
});
$("a").on("mouseleave", function() {
$('#cursor').removeClass("active");
$('#stalker').removeClass("active");
});
});
}
最後に
今回は初めてマウスポインターにアニメーションをつけてみました。
たったこれだけでサイトにオリジナリティがでるんじゃないでしょうか。
cssでさらに動きを追加したり、画像を追従させたりもできるのでぜひ試してみてください。
それでは。