onmouseover,显示图片的大版本

时间:2015-11-15 18:44:57

标签: javascript html onmouseover

当您将鼠标悬停在较小版本的图片上时,我试图显示大图片版本。我目前有4个功能来做这个,但想知道是否可以通过使用一个来完成。问题是,如果我只有一个功能,我不知道如何更改源路径。我的代码如下。

HTML :(我只有鼠标悬停的第一张带有showImage()的图片用于测试目的)

<section>
        <article>
            <header>Mouse Over and Mouse Out Events</header>
            <img onmouseover="showImage()" onmouseout="hideImage()" id="one" src="images/small/catbread1.jpg" title="catbread1" alt="Cat with bread on face 1" /> <img onmouseover="bigImage2()" onmouseout="hideImage()" id="two" src="images/small/catbread2.jpg" alt="Cat with bread on face 2" />
            <img onmouseover="bigImage3()" onmouseout="hideImage()" id="three" src="images/small/catbread3.jpg" alt="Cat with bread on face 3" /> <img onmouseover="bigImage4()" onmouseout="hideImage()" id="four" src="images/small/catbread4.jpg" alt="Cat with bread on face 4" />
        </article>
        <article>
            <header>Cat Photos</header>
            <img id="full" src="" />
        </article>

使用Javascript:

function hideImage() {
    document.getElementById("full").src = "";
}

function bigImage1() {
    document.getElementById("full").src = "images/large/catbread1.jpg";
}

function bigImage2() {
    document.getElementById("full").src = "images/large/catbread2.jpg";
}

function bigImage3() {
    document.getElementById("full").src = "images/large/catbread3.jpg";
}

function bigImage4() {
    document.getElementById("full").src = "images/large/catbread4.jpg";
}

function showImage() {
    document.getElementById("full").src = "images/large/" + this.title + ".jpg";
}

2 个答案:

答案 0 :(得分:2)

看起来您已将图像排列为large/small/的并行层次结构 - 这很好,它会让这很容易,而您几乎已经在{{{ 1}}。我将使用一些stock photos构建此示例,因此它明显有用。

基本上你想做的是:

  • 抓住已被淹过的图像
  • showImage
  • 替换其路径的small/部分
  • 将其分配给large/元素

要获取已被鼠标悬停的图像,请在full事件期间将其传递给showImage。触发事件的元素以onmouseover形式提供。

this

<img onmouseover="showImage(this)" onmouseout="hideImage()" src="https://static.pexels.com/photos/9413/animal-cute-kitten-cat-small.jpg" /> 接受参数,您可以使用showImage进行路径转换,然后按照原来的方式将其分配给replace()

full

将此代码段打开以进行演示:

function showImage(img) {
  var src = img.src;
  var largeSrc = src.replace('small', 'large');
  document.getElementById('full').src = largeSrc;
}
function hideImage() {
  document.getElementById("full").src = "";
}

function showImage(img) {
  var src = img.src;
  var largeSrc = src.replace('small', 'large');
  document.getElementById('full').src = largeSrc;
}

答案 1 :(得分:1)

为什么不尝试使用简单的CSS?

&#13;
&#13;
.badboy {
  background : url( http://g02.a.alicdn.com/kf/HTB16ENqIXXXXXaUXVXXq6xXFXXXp/1000-autumn-maples-font-b-fall-b-font-font-b-scenery-b-font-jigsaw-puzzle-casual.jpg);
width: 300px;
height : 150px;
  margin: 0 auto;
  display: block;
  transition : ease all .5s
}

.badboy:hover {
   background : url( http://media-cdn.tripadvisor.com/media/photo-s/01/48/61/6c/beautiful-scenery-around.jpg);
width: 400px;
height : 250px;
  }
&#13;
<div>
<img class="badboy">
</div>
&#13;
&#13;
&#13;