如何根据图像的高度翻译图像?

时间:2016-06-10 09:25:41

标签: javascript html css

我有一个高大的形象,在一个不高的div中。我想通过翻译来展示整个图像。这就是我到目前为止所做的:

https://jsfiddle.net/swv0w0em/



 document.addEventListener("mouseover", function(event) {
   var element = event.target;
   if (element.classList.contains("myImage") &&
     element.naturalWidth < element.naturalHeight) {
     element.className += " imageScroll";


     //element.style.transform = "translate(0,-" + element.naturalHeight + ")";
     //element.style.mozTransition = "translate(0,-" + element.naturalHeight + ")";
     //element.style.msTransform = "translate(0,-" + element.naturalHeight + ")";
     //element.style.oTransform = "translate(0,-" + element.naturalHeight + ")";
     //element.style.webkitTransform = "translate(0,-" + element.naturalHeight + ")";
   }
 });
 document.addEventListener("mouseout", function(event) {
   var element = event.target;
   if (element.classList.contains("myImage")) {
     element.className = element.className.replace(
       /(?:^|\s)imageScroll(?!\S)/g, ''
     );
   }
 });
&#13;
div {
  height: 200px;
  overflow: hidden;
  background-color: red;
}
img {
  -moz-transition: all 3s ease-in-out;
  -o-transition: all 3s ease-in-out;
  -webkit-transition: all 3s ease-in-out;
  transition: all 3s ease-in-out;
}
.imageScroll {
  -moz-transform: translate(0, -350px);
  -ms-transform: translate(0, -350px);
  -o-transform: translate(0, -350px);
  -webkit-transform: translate(0, -350px);
  transform: translate(0, -350px);
}
&#13;
<div>
  <img src="https://placeimg.com/300/800/any" class="myImage" alt="SomeImage">
</div>
&#13;
&#13;
&#13;

但是,我无法弄清楚如何使用图像高度进行翻译。我希望只要图像的底部在视图中,滚动就会停止。我不知道之前的图像有多高,所以我无法在CSS中对其进行硬编码。这就是为什么我尝试在JavaScript中设置样式,但这对我不起作用(请参阅注释掉的代码)。

我的问题:如何在鼠标悬停时让图像一直向下滚动,并在到达图像底部时停止滚动?我也无法滚过高处,或者我会得到丑陋的白色空间。我试图在纯JavaScript中完成此操作,没有jQuery 。谁可以帮忙?

2 个答案:

答案 0 :(得分:2)

使用纯CSS,您可以在翻译中使用百分比单位,然后使用顶部偏移量(绝对位置)减去容器的高度:

&#13;
&#13;
div {
  height: 200px;
  overflow: hidden;
  position: relative;
}

.myImage {
  transition: all 3s ease-in-out;
  display: block;
  position: absolute;
  top: 0; left: 0;
}

.myImage:hover {
  top: 100%;
  transform: translateY(-100%);
}
&#13;
<div>
  <img src="https://placeimg.com/300/800/any" class="myImage" alt="SomeImage">
</div>
&#13;
&#13;
&#13;

jsFiddle:https://jsfiddle.net/azizn/h37dLzgf/1/

答案 1 :(得分:0)

注释掉的代码缺少&#34; px&#34;

 element.style.transform = "translate(0,-" + element.naturalHeight + "px)";
 element.style.mozTransition = "translate(0,-" + element.naturalHeight + "px)";
 element.style.msTransform = "translate(0,-" + element.naturalHeight + "px)";
 element.style.oTransform = "translate(0,-" + element.naturalHeight + "px)";
 element.style.webkitTransform = "translate(0,-" + element.naturalHeight + "px)";