javascript - 鼠标悬停和鼠标高度上的图像叠加?

标签 javascript css

我想要在图像上叠加,直到鼠标高度。

w3schools 在这里有一个很好的图像叠加演示,这对我想要的有很大帮助。

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_image_overlay_slidebottom

这里的覆盖高度定义为

.container:hover .overlay {
  height: 100%;
}

有没有一种方法可以定义高度,使其上升到图像的高度,假设鼠标在图像上?

最佳答案

您可以使用 jQuery 获得此行为

$("div.container").mousemove(function(e){
  var avatarImg = $("#avatar");
  var avatarPosition = avatarImg.offset();
  var mousePositionX = e.pageX - avatarPosition.left;
  var mousePositionY = e.pageY - avatarPosition.top;
  var overlayNewHeight = avatarImg.height() - mousePositionY;
  $("div.overlay").height(overlayNewHeight);
});


$("div.container").mouseleave(function(){
  $("div.overlay").height(0);
});
.container {
  position: relative;
  width: 50%;
  margin-left: 100px;
  margin-top: 100px;
  border: black solid 1px;
}

#avatar {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<body>

<h2>Slide in Overlay from the Bottom</h2>
<p>Hover over the image to see the effect.</p>

<div class="container">
  <img src="https://i.imgur.com/I80W1Q0.png" alt="Avatar" class="image" id="avatar">
  <div class="overlay">
    <div class="text">Hello World</div>
  </div>
</div>

<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
</body>

关于javascript - 鼠标悬停和鼠标高度上的图像叠加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367501/

相关文章:

html - 在列方向上的 flexbox 中的内联 block

html - 另一个带有干净代码的粘性页脚/100% 高度 div

css - float 元素旁边的 Bootstrap 3 导航

Javascript - 单击时更改图像,再次单击按钮时返回相同的图像

javascript - HTML5 Canvas - 在不转换上下文的情况下相对于对象的中心进行缩放

javascript - Unicode 中数字 93 有何含义?

html - 悬停在链接后面的图像

javascript - 通过 mailto URI 附加文件

javascript - 我想在 Jquery 中查看此 $.get() ajax 函数的源代码

javascript - 平滑滚动+按钮 'onclick' 功能