WordPress使用jQuery 按比例调整图片高度/宽度

同学们,今天我们来谈谈WordPress主题制作的细节问题:限制文章中图片的最大宽度,防止图片“撑破”页面,用的比较多的方法是在CSS中使用 overflow:hiddenmax-width:600px 来限制,但是效果不理想,倡萌今天分享一下比较完美的方法: jQuery 按比例调整图片高度/宽度。

2013-4-14更新:使用 max-width 也是可以按等比缩小图片的。以前倡萌之所以任务无法实现,是因为我自己使用WLW离线发布时,使用WLW定义了图片的格式,而没办法继承样式表的样式。特此说明,希望大家不要被误导!

三种方法的效果比较

wpdaxue.com-201210074

从上图可以看出,overflow 仅仅是隐藏了部分图片,导致图片显示不全;max-width 只是限制的最大宽度,图片压缩变形;而jQuery 却可以等比例调整图片的高和宽,图片没有变形,这就是我们要的效果!

等比例调整图片的高和宽

方法一:jQuery 代码(荐)

现在大部分的网站都使用了 jQuery 库,所以我们只需添加下面的 jQuery 代码即可实现:

$(document).ready(function() {
    $('.post img').each(function() {
    var maxWidth = 600; // 图片最大宽度
    var maxHeight = 2000;    // 图片最大高度
    var ratio = 0;  // 缩放比例
    var width = $(this).width();    // 图片实际宽度
    var height = $(this).height();  // 图片实际高度
 
    // 检查图片是否超宽
    if(width > maxWidth){
        ratio = maxWidth / width;   // 计算缩放比例
        $(this).css("width", maxWidth); // 设定实际显示宽度
        height = height * ratio;    // 计算等比例缩放后的高度
        $(this).css("height", height * ratio);  // 设定等比例缩放后的高度
    }
 
    // 检查图片是否超高
    if(height > maxHeight){
        ratio = maxHeight / height; // 计算缩放比例
        $(this).css("height", maxHeight);   // 设定实际显示高度
        width = width * ratio;    // 计算等比例缩放后的高度
        $(this).css("width", width * ratio);    // 设定等比例缩放后的高度
    }
    });
});

实际使用时,注意修改 $(‘.post img’) 为你文章内容的class值,以及最大宽度、高度。

关于jQuery 库,请阅读《WordPress提速:选择好的jQuery库(Google/Microsoft/SAE)

方法二:纯Javascript代码

<script type="text/javascript">
function ResizeImage(image, 插图最大宽度, 插图最大高度)
{
    if (image.className == "Thumbnail")
    {
        w = image.width;
        h = image.height;
 
        if( w == 0 || h == 0 )
        {
            image.width = maxwidth;
            image.height = maxheight;
        }
        else if (w > h)
        {
            if (w > maxwidth) image.width = maxwidth;
        }
        else
        {
            if (h > maxheight) image.height = maxheight;
        }
 
        image.className = "ScaledThumbnail";
    }
}
</script>

实现效果和上面一样,不需要引用 jQuery 库,请设置最大高度和宽度值;在发布文章时,要手动给每张图片添加一个 class=”Thumbnail”

好了,今天课程到此为止,如果你有更好的方法,欢迎投稿分享!

来源:

https://www.wpdaxue.com/jquery-resize-image.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32851.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?