问题描述:

I have a container div of size 150x150 which contains an image of size 150x180. The div has overflow: hidden css property enabled so a part of the image is hidden. Div size is fixed 150x150, image height may vary from image to image though. When I hover on the div or image, I want to vertically move the image so that the hidden part of the image could be shown to the viewer.

To make this functionality work I've used jQuery. Here's what I'm doing (my css, html, jQuery code blocks):

$("#container").mouseenter(function() {

img_height = $(this).find('img').height();

$(this).find('img').animate({

'top': 150 - img_height

}, 300);

});

$("#container").mouseleave(function() {

$(this).find('img').animate({

'top': 0

}, 300);

});

#container {

width: 150px;

height: 150px;

overflow: hidden;

border: 1px solid;

position: relative;

}

#container img {

position: absolute;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">

<img class="fl" src="http://media.dcentertainment.com/sites/default/files/superman-150x180.jpg" width="150"/>

</div>

网友答案:

Try this. The main idea is setting initial vertical offset in style when image will be loaded.

<img onload="this.style.bottom = '' + (150 - this.offsetHeight) + 'px' src="..." />

But it is not entirely pure HTML/CSS solution.

.container {
    width: 150px;
    height: 150px;
    position: relative;
    overflow: hidden;
}

.container img {
    position: absolute;
    transition: bottom 0.3s;
}

.container img:hover {
    bottom: 0 !important;
}
<div class="container">
    <img src="http://media.dcentertainment.com/sites/default/files/superman-150x180.jpg" onload="this.style.bottom = '' + (150 - this.offsetHeight) + 'px'" />
</div>
网友答案:

height 100% should do the trick!

#container {
    width: 150px;height: 150px;overflow: hidden;border: 1px solid;position: relative;
}
#container img:hover { 
    height:100%;
}
<div id="container"><img class="fl" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQiWGXo4U6CCvNItlDYFgEQz4d3T-YjLj13nqUZ-crpAr3qMPx-"/>
</div>
网友答案:
  1. Use transition on image.
  2. Use fixed px height for the div that contains image.
  3. No use to absolute position the image(only required if there are other elements inside the div

Here is the code

<div class="imgWrap">
  <img src="http://lorempixel.com/g/150/180" alt="" class="img1"> 
</div>

and here is css code

.imgWrap{
  width:150px;
  height:150px;
  overflow:hidden;
}
.img1{

  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}
.imgWrap:hover .img1{
  margin-top:-30px
}

I have created a pen for this http://codepen.io/Prashantsani/pen/BywmoN

相关阅读:
Top