如何在保持鼠标悬停功能的同时居中跨过图像

How to center span over image while maintaining mouseover functionality

本文关键字:图像 功能 悬停 鼠标      更新时间:2023-09-26
<div class="pic">
    <img src="image.jpg" height="250"/>
    <span class="text" style="display:none">text here</span>
</div>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
</script>
<script type="text/javascript">
    $('img').css('opacity', 0.4);
    $('img').next('span.text').show();
    $('img').bind('mouseover', function () {
        $(this).css('opacity', 1.0);
        $(this).next('span.text').hide();
    });
    $('img').bind('mouseout', function () {
        $(this).css('opacity', 0.3);
        $(this).next('span.text').show();
    });
</script>

我有一个不透明的图像,在mouseover上完全可见。我添加了跨度的文本,这些文本将在mouseover上消失,并在mouseout上重新出现,类似于图像上的不透明性。我试图在 CSS 中用 margin-left:automargin-right:auto将文本居中,但缺乏结果。有没有办法使文本居中,同时仍然具有不透明度并且文本在mouseover上消失?Javascript是最好的方法吗?

谢谢

你不能

用CSS做到这一点吗?

body {
  text-align: center;
}
.pic {
  display: inline-block;
  margin: 25px;
  border: 1px solid red;
  position:relative;
}
.pic img {
  display: block;
  opacity: 0.4;
  transition: opacity 0.5s ease;
}
.text {
  opacity: 1;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  transition: opacity 0.5s ease;
}
.pic:hover img {
  opacity: 1;
}
.pic:hover .text {
  opacity: 0;
}
<div class="pic">
  <img src="http://lorempixel.com/output/city-q-c-250-250-7.jpg" />
  <span class="text">text here</span>
</div>