LoginSignup
0
0

More than 5 years have passed since last update.

[javascript]image上にmouseoverで文字をかぶせる

Last updated at Posted at 2017-10-17

image上にmouseoverで文字をかぶせる

仕様

  • imgタグのaltをimgタグにmouseoverしたとき表示する
  • figure,figcaptionを利用
  • 面倒がおおいのでjQueryを利用
  • 画像サンプルはplacehold.jpを利用

ソース

HTML

test_4.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="test_4.js"></script>
<title>test_4:image上にmouseoverで文字をかぶせる</title>
</head>
<body>
<div class="myimage">
<img src="https://placehold.jp/ff0000/00ffff/150x150.png?text=1" class="alt_text" alt="あああ">
<img src="https://placehold.jp/00ff00/ff00ff/300x200.png?text=2" class="alt_text" alt="いいい">
<img src="https://placehold.jp/0000ff/ffff00/100x80.png?text=3" class="alt_text" alt="ううう">
</div>
</body>
</html>

javascript

test_4.js
$(function () {
  $('.myimage img').on({
    'mouseover':function () {
      var w=$(this).width();
      $(this).filter(function(){
        return $(this).closest('figure').length==0;
      }).wrap(
        $('<figure>').css({
          "display":"inline-block",
          "position":"relative",
          "margin":"0px"
        })
        );
      $(this).filter(function(){
        return $(this).next('figcaption').length==0;
      }).after(
        $('<figcaption>').css({
          "font-size":"0.7em",
          "position":"absolute",
          "bottom":"20px",
          "left":"0px",
          "color":"#ffffff",
          "background":"rgba(0,0,0,0.6)",
          "width":"100%",
          "max-width":w+"px",
          "padding":"1em 0px",
          "text-align":"center"
          }).text($(this).attr('alt'))
        );
    },
    'mouseout':function () {
      $(this).next('figcaption').remove();
      $(this).unwrap();
    },
  });
});
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