WordPress 文章内容图片自适应大小缩放的方法

84 教程

关于wordpress主题开发中文章图片自适应的问题已经是老生常谈了,今天三种方法给大家,希望能帮助大家解决手头的问题,其它也没有什么创新的方法,还是css与jquery的解决方法。

推荐方法:运用用官方默认CSS样式

将以下代码复制粘贴到主题style.css文件内即可
强制最大化宽度为600px,高度为相对高度,通过以上设置不失为一个最佳的解决方案

p img {
max-width:600px;
width: expression(this.width > 600 ? “600px” : true);
height:auto;
}

p img {width:600px;height:auto;}

通过jQuery库来实现图片自适应

首先我们要加载jquer库,然后以下面的代码添加到wordpress主题中的header.php文件中。
可以对图片进行自动缩放,方法较为完美。

$(document).ready(function(){
    $('div').autoResize({height:750});
});  
jQuery.fn.autoResize = function(options)
{
    var opts = {
        'width' : 700,
        'height': 750
    }
    var opt = $.extend(true, {},opts,options || {});
    width = opt.width;
    height = opt.height;
    $('img',this).each(function(){
        var image = new Image();
        image.src = $(this).attr('src');   if(image.width > 0 && image.height > 0 ){
            var image_rate = 1;
            if( (width / image.width) < (height / image.height)){
                image_rate = width / image.width ;
            }else{
                image_rate = height / image.height ;
            }
            if ( image_rate <= 1){
                $(this).width(image.width * image_rate);
                $(this).height(image.height * image_rate);
            }
        }
    });
}

这两种方法可以说都通过各自的方式达到了我们想要的效果,同时还是推荐第一种,因为第二种对于不了解代码的同学,操作成本还是比较大的。