在网页中用鼠标放大缩略图的简单方法



我的项目有很多页面,上面有很多图像缩略图。尺寸为150x150。我们希望网站在悬停在每个缩略图上时弹出一个全尺寸的图像。我想知道实现这一点的最简单方法,无论是使用HTML、JavaScript还是CSS,以及开始使用它并使其运行的基本步骤。

我正在寻找一个简单的解决方案,记住我的技能是一些基本的JavaScript和HTML,我不熟悉CSS的工作原理。

尝试删除mouseover上的宽度和高度属性,并在mouseout上恢复它们。

$("img").mouseover(function() {
    this.setAttribute("data-width", this.width);
    this.setAttribute("data-height", this.height);
    this.removeAttribute("width");
    this.removeAttribute("height");
});
$("img").mouseout(function() {
    this.setAttribute("width", this.getAttribute("data-width"));
    this.setAttribute("height", this.getAttribute("data-height"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img height="25" width="25" src="https://www.gravatar.com/avatar/a5563b966d383529a65612e6590f957f?s=128&d=identicon&r=PG">

几个注意事项:

  1. 您不需要jQuery,但我在这里使用它是为了避免处理浏览器之间事件模型的差异
  2. 您可能不希望对每个图像都执行此操作。在这种情况下,将img替换为类,如.hoverable

一个更紧凑的版本,使用更多的jQuery函数:

$("img").hover(function() {
    $(this).attr({
        'data-width': this.width,
        'data-height': this.height
    }).removeAttr('width').removeAttr('height');
}, function() {
    $(this).attr({
        width: $(this).attr('data-width'),
        height: $(this).attr('data-height')
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img height="25" width="25" src="https://www.gravatar.com/avatar/a5563b966d383529a65612e6590f957f?s=128&d=identicon&r=PG">

我会考虑使用类似lightbox的库(http://lokeshdhakar.com/projects/lightbox2/)或jquery缩放(http://www.jacklmoore.com/zoom/)

最新更新