繁体   English   中英

如何改变图像大小?

[英]How to change size of images?

当用户将鼠标悬停在图像上时,我试图放大图片,并在用户输出图像后缩小图像尺寸。

我有以下代码

$('#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%'});
});

当您更改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%');
});

你想要实现的并不像看起来那么容易。 如果要将原点保持在容器的中心,则需要将图像相对于容器绝对定位。 尝试使用这个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/

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

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

为了做到这一点,您需要将图像水平和垂直居中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM