[英]How to show different images using .hover() jQuery
我将尝试解释我的问题:
我有span元素,每个span元素都有文本,当用户将其悬停时,它应该在该元素旁边显示一个图像,每个图像都是不同的,我试图使用jQuery .hover()
函数,但是当我将鼠标悬停在文字显示了整个图像。
我该如何解决?
我的HTML。
<table>
<tbody>
<tr>
<td style="width: 20%;" class="text-center">
<span class="displayImage">Azotea </span>
<span class="displayImage">Nivel 8 </span>>
</td>
</tr>
</tbody>
</table>
<div class="col-lg-5 text-left">
<img class="displayed" src="images/azotea-n9.jpg" alt="">
<img class="displayed" src="images/test2.jpg" alt="">
</div>
我的代码。
$(".displayImage").hover(function(){
$(".displayed").show();
}, function () {
$(".displayed").hide();
});
谢谢!。
您可以通过数据属性和ID将跨度与特定图像相关联。
$(".displayImage").hover(function(){ // $(this).attr('data-img') == 'azotea' or 'nivel8' // so we end up with $('#azotea').show(), for example. $('#' + $(this).attr('data-img')).show(); }, function () { $('#' + $(this).attr('data-img')).hide(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <td style="width: 20%;" class="text-center"> <span class="displayImage" data-img='azotea'>Azotea </span> <span class="displayImage" data-img='nivel8'>Nivel 8 </span> </td> </tr> </tbody> </table> <div class="col-lg-5 text-left"> <img class="displayed" src="images/azotea-n9.jpg" alt="azotea" id="azotea"> <img class="displayed" src="images/test2.jpg" alt="nivel 8" id="nivel8"> </div>
我尝试不要更改您的html
https://jsfiddle.net/luarmr/hjreda3r/
我还添加了一些CSS,以便从原点隐藏元素
$(".displayImage").hover(
function(el){
var image = $(this).data('ref');
$(".displayed:nth-child(" + image + ")").show();
}, function () {
$(".displayed").hide();
}
);
我建议您更好地使用css3而不是jquery,因为cos jquery会降低您的网站在移动设备上的生产力,因此也许您应该看看此处在此处输入链接描述
您需要找到span
和image
之间的共同点, 而无需在标记中添加任何额外内容,这将是它们各自的index
值。 显然,我在下面建议的此解决方案完全取决于您布置HTML的顺序。
看看我发布的类似问题的解决方案 。
因此,基本上,您的代码应如下所示:
$(".displayed").hide(); $(".displayImage").hover(function(){ $(".displayed").eq($(this).index()).show(); },function(){ $(".displayed").eq($(this).index()).hide(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tbody> <tr> <td style="width: 20%;" class="text-center"> <span class="displayImage">Azotea </span> <span class="displayImage">Nivel 8 </span> </td> </tr> </tbody> </table> <div class="col-lg-5 text-left"> <img class="displayed" src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/JS.jpg" alt=""> <img class="displayed" src="https://dl.dropboxusercontent.com/u/45891870/Experiments/Codepen/PIXI/0.4/images/PIXI.jpg" alt=""> </div>
希望它能有所帮助。
Ť
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.