如何更改图像的大小

How to change size of images?

本文关键字:图像 何更改      更新时间:2023-09-26

当用户将鼠标悬停在图像上时,我正在尝试放大图片,并在用户鼠标悬停图像后减小图像的大小。

我有以下代码

$('#image_layout').on('hover','img',function(){
    $(this).css('width','110%');
})
$('#image_layout').on('mouseout','img',function(){
    $(this).css('width','90%');
})
我想从图像

的中心位置放大图像,而不是从图像的顶部位置放大图像。

我有的那个:

 ----        ------
|    |  ->  |      |
 ----       |      |
             ------

我想要的那个:(从图像中心放大图片)

               ------
   ----       |      | 
  |    |  --> |      |
   ----       |      |
               ------

我不确定如何实现这一目标。有什么提示吗?多谢!

避免将 JavaScript 用于可以通过简单的 CSS 调整来处理的任务,不要让页面上 JavaScript 的重量变得沉重。

#image_layout 
{
   width : /* initial width value */ 
   height: /* initial height value */
}

#image_layout : hover
{
   width : /* new width value */ 
   height: /* new height value */
   /* use of multiple tranistions */
   transition : all 0.2s ease-out 
}

关于jQuery的方式,不需要应用.css()两次,只需向其传递一个包含属性及其值的对象:

$('#image_layout').on('mouseout','img',function(){
    $(this).css({'width':'90%', 'height':'100%'});
});

你想要实现的目标并不像看起来那么容易。如果要将原点保持在容器的中心,则需要相对于容器绝对定位图像。尝试使用此 lil' 插件,它可能不会适用于所有情况,但值得一试。

$.fn.centerIt = function(){
    var height = this.outerHeight(),
        width = this.outerWidth();
    this.css({
        position: 'absolute',
        top: '50%',
        left: '50%',
        marginTop: -(height/2),
        marginLeft: -(width/2)
    })
    .parent()
    .css('position', 'relative');
    return this;    
};
$('img').css('width', '90%').centerIt();

演示:http://jsfiddle.net/elclanrs/RMsSh/

当您更改width并且尚未定义height时,浏览器会自动保持它们之间的比例,因此height也将110%90%

试试这个代码:

$('#image_layout').on('hover','img',function(){
    $(this).css('width','110%')
        .css('height','100%')
});
$('#image_layout').on('mouseout','img',function(){
    $(this).css('width','90%')
        .css('height','100%');
});

在 JQuery 中更改图像大小非常简单。您可以使用此方法或 CSS 方法。CSS()

$('#imageId').width(150).height(100);

您需要让图像水平和垂直居中才能做到这一点。