使用 onmouseover 更改图像大小 wp_get_attachment_image

Using onmouseover to change image size with wp_get_attachment_image involved

下面是我用来显示多行产品的部分代码,每个产品旁边都有微小的缩略图(35x35 像素)。这是我创建的管理页面,很像用于管理产品的电子表格,所以 space 它们占用的空间越少越好。

一切正常,但我想让客户"mouseover"查看更大的图像。我了解如何 "onmouseover" and/or 与 CSS 一起使用来实现图像的放大,但通常是使用传统的 <img src... > 元素。

甚至可以改变或利用 wp_get_attachment_image 来达到同样的效果吗?我不能简单地将代码粘贴到 <img> 元素中,因为它的 "not there",可以这么说,输入(抱歉我缺乏术语,但我认为这是一个函数而不是静态代码我可以使用)。

或者,有没有办法不设置数组 (35,35) 而只是使 <li> 成为特定大小的容器,使图像填充该容器,然后使用该元素来执行图片改动?

if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
       $thumbimg = wp_get_attachment_image( $attachment->ID, array(35,35) );
       $productlist .= '<li style="display: inline-block; vertical-align: top; margin: 0px; margin-right: 7px;">' . $thumbimg . '</li>';
    }
}

我以前用两种不同的方式做过:

1。将图像显示为背景图像

PHP: (注意我已经移动了你的内联 css 以便更容易看到代码更改)

if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        $thumbimg = wp_get_attachment_image_src( $attachment->ID, array(35,35) );
        $productlist .= '<li class="prodimgcontainer" style="background-image:url('.$thumbimg[0] .')"></li>';
    }
}

CSS:

.prodimgcontainer{
    width: 35px; 
    height: 35px; 
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100%;

    // your inline css: 
    display: inline-block; vertical-align: top; margin: 0px; margin-right: 7px;
}
.prodimgcontainer:hover{
    background-size: 105%;
}

2。在容器元素上使用 overflow:hidden 到 "crop" 图像的可见部分

PHP:

if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        $thumbimg = wp_get_attachment_image( $attachment->ID, array(35,35) );
        $productlist .= '<li class="prodimgcontainer">' . $thumbimg . '</li>';
    }
}

CSS:

.prodimgcontainer{
    width: 35px; 
    height: 35px; 
    overflow: hidden;

    // your inline css: 
    display: inline-block; vertical-align: top; margin: 0px; margin-right: 7px;
}
.prodimgcontainer img{
    width: 35px;
}
.prodimgcontainer img:hover{
    width: 39px;
    height: 39px;
    /* move the position of the image slightly so it remains centered */
    margin-top: -2px;
    margin-left: -2px;
}

这也适用于百分比,但由于您的图像是固定宽度的,所以我使用了这些尺寸,以便更清楚地了解正在发生的事情。

注:

这些例子是基于我所做的工作,所以这个概念在这两种情况下都是有效的并且应该有效,但是,我已经让他的代码更改脱离了我的头脑,所以它没有经过测试.

我发现选项 1 可以更轻松地处理图像,尤其是在图像尺寸不同或需要响应时。