0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jQueryでマウスに追従するツールチップを作成してみた

Posted at

css

style.css
.tooltip {
    position: absolute;
    padding: 20px;
    background-color: #fff;
    border-radius: 10px;
    border: 2px #CCC solid;
}
.tooltip-body {
    position: relative;
    line-height: 1.5;
    margin: 20px;
    cursor: pointer;
}

html,jquery

index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title></title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/base.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="tooltip-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit.<br>Accusamus, provident harum commodi nam fugiat blanditiis natus similique odio minima eius tenetur, facilis sit amet, alias nemo pariatur modi ab facere.</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
// .tooltip-bodyにマウスが乗ったら、
//<div class='tooltip' style='display: none;'>description</div>
// がfadeInし、マウスが外れたらfadeOutする。
// その際に.tooltipがマウスに追尾する。
// mousemove マウスの移動座標を取得できる
// .hover() ホバー時の処理を指定
// prepend()要素内の先頭に要素を追加
$(function(){
  var ttb = $(".tooltip-body");
  ttb.prepend("<div class='tooltip' style='display: none;'>description</div>");//.tooltip-body内の先頭に.tooltipを追加
  var tt = $(".tooltip")
  ttb.hover(function(){ //ホバー時の処理
    tt.stop(true,false);//アニメーションを止める。stop(現在のアニメーションをゴールまでジャンプさせるか否か,待機状態のアニメーションを破棄するか否か)
    tt.fadeIn(); //.tooltipを表示
    $(this).mousemove(function(e){//mousemoveでマウスの座標を取得
      tt.css({
        top : e.pageY,//縦軸をtopに設定
        left : e.pageX//横軸をleftに設定
        //これでツールチップがマウスに追従する
      });
    });
  },function(){
    tt.stop(true,false);
    tt.fadeOut();//マウスが離れたら非表示
  });
});

</script>
</body>
</html>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?