图像在悬停时滚动

问题描述 投票:1回答:2

我想在div中创建图像以在悬停时向下滚动。那部分正在发挥作用。

此外,如果图像较长,我需要使其滚动更长,因此我尝试在转换中使用calc,但它不起作用。

这是我的代码:

HTML

<div class="preview">
    <div class="previewimg"></div>
</div>

CSS

.preview {
 position: relative;
 width: 75%;
 height:90vh;
 overflow: hidden;
 border:1px solid red;
 background-color: transparent;
 }
.previewimg {
 width: 100%;
 height: 100%;
 top:0;
 background-image: url(https://www.n2odesigns.com/wp-
content/uploads/Projema-Website-Preview-2016.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position-y: 0;
transition:all calc(0.02s * height) ease-in-out;
}
.previewimg:hover {
background-position-y: 100%;
height: 100%;
transition:all calc(0.02s * height) ease-in-out;
}

如果还有其他更好的方法,我也可以使用它。在此先感谢您的帮助!

css hover css-transitions css-animations transition
2个回答
3
投票

好的,你需要它只是一个图像而不是背景图像,要根据高度功能完成这个转换持续时间,请使用下面的代码。

$('.previewimg').css("transition", "transform " + 0.02 * $('.previewimg').height() + "s ease");
.preview {
  position: relative;
  width: 75%;
  height: 300px;
  overflow: hidden;
  border: 1px solid red;
  background-color: transparent;
}

.preview .previewimg {
  width: 100%;
  height: auto;
  transform: translateY(0px); 
}

.preview:hover .previewimg {
  transform: translateY(calc(-100% + 300px)); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preview">
  <img class="previewimg" src="https://www.n2odesigns.com/wp-content/uploads/Projema-Website-Preview-2016.jpg"/>
</div>

3
投票

如果您接受JS作为解决方案,那么这里是您可以添加而无需更改HTML / CSS结构的代码:

function getHeight(url) {
  console.log(url);
  var img = new Image();
  img.src = url;
  return 0.002*parseInt(img.height);
}
var e =$(".previewimg");
var tr = "all "+getHeight(e.css("background-image").replace(/^url\(['"](.+)['"]\)/, '$1'))+"s ease-in-out";
console.log(tr);
e.css('transition',tr);
.preview {
  position: relative;
  width: 75%;
  height: 90vh;
  overflow: hidden;
  border: 1px solid red;
  background-color: transparent;
}

.previewimg {
  width: 100%;
  height: 100%;
  top: 0;
  background-image: url(https://www.n2odesigns.com/wp-content/uploads/Projema-Website-Preview-2016.jpg);
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position-y: 0;
}

.previewimg:hover {
  background-position-y: 100%;
  height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preview">
  <div class="previewimg"></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.