Javascript图像翻转 - 需要标题,如何添加它们?

时间:2017-10-24 20:21:10

标签: javascript html css

我使用javascript制作一种假期幻灯片,其中主要图片会根据您悬停的链接而改变。我还是javascript的新手,并且花了最后两个小时试图弄清楚如何让图片现在显示下面的标题,我真的很喜欢一些帮助。

这是我的js文件:

var canadaOver = new Image();
canadaOver.src = 'images/canada.jpg';
var italyOver = new Image();
italyOver.src = 'images/italy.jpg';
var ukraineOver = new Image();
ukraineOver.src = 'images/ukraine.jpg';
var japanOver = new Image();
japanOver.src = 'images/japan.jpg';
var icelandOver = new Image();
icelandOver.src = 'images/iceland.jpg';
document.getElementById("canada").onmouseover = doMouseOver;
document.getElementById("italy").onmouseover = doMouseOver;
document.getElementById("ukraine").onmouseover = doMouseOver;
document.getElementById("japan").onmouseover = doMouseOver;
document.getElementById("iceland").onmouseover = doMouseOver;


function doMouseOver(evt)  {
var anchor = evt.target || evt.srcElement;
var img = document.getElementById("destinations");
var textDiv = document.getElementById('caption');
if (anchor.id == "canada")    {
        img.src = canadaOver.src;
    }
    else if (anchor.id == "italy")
    {
        img.src = italyOver.src;
        textDiv.innerHTML = imgText;
    }
    else if (anchor.id == "ukraine")    {
        img.src = ukraineOver.src;
        textDiv.innerHTML = imgText;
        }
    else if (anchor.id == "japan")    {
        img.src = japanOver.src;
        textDiv.innerHTML = imgText;
        }
    else if (anchor.id == "iceland")    {
        img.src = icelandOver.src;
        textDiv.innerHTML = imgText;
        }
        }

我的链接位于主图像旁边的表格中。我只是无法弄清楚字幕的位置!

1 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西

https://jsfiddle.net/84cfy1Lf/

HTML

<body>
  <section id="country-stuff">

  </section>
</body>

SCRIPT

var countries = ['canada', 'italy', 'ukraine', 'japan', 'iceland'];

countries.forEach(function(country) {
  var img = document.createElement('img');
  img.id = country;
  img.className = 'image';
  img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/CallingCodesWorld-Labeled.svg/500px-CallingCodesWorld-Labeled.svg.png' // swap for real image director:  images/' + country +'.jpg';

  var mouser = document.getElementById('country-stuff').appendChild(img);

  mouser.addEventListener('mouseover', function(event) {
    doMouseOver(event);
  })
});

var caption = document.createElement('div');
caption.id = 'caption';
document.getElementById('country-stuff').appendChild(caption);


function doMouseOver(event) {
  var anchor = event.target;
  populateCountryText(anchor)
}


function populateCountryText(anchor) {
  document.getElementById('caption').innerHTML = event.target.id;

  return caption;
}

CSS

.image {
  width: 150px;
}