根据属性中指定的图像大小动态更改图像

Change image dynamically on the basis of its size specified in attribute

本文关键字:图像 动态 属性      更新时间:2023-09-26

我正在构建一个CMS系统,用户可以在其中管理和上传图像以显示在博客上。

为了提高效率,我创建了三个不同大小的图像版本。但最终用户对此一无所知

我想要的是,当wyswyg编辑器用户更改其尺寸时,图像URL应该相应地更改,以适合"图标"、"拇指"answers"大"类型的图像。我可以通过解析服务器端的内容来做到这一点,但在客户端没有任何标准的方法吗?

假设您的图像有这样的url:http://example.com/image.jpg

你可以做一些类似的事情

$(document).ready(function(){
    $('img').each(function(){
        var src = $(this).attr('src');
        //the extension of the image (e.g. png, gif, jpeg)
        var extension = src.substr( (src.lastIndexOf('.') +1) );
        //the path to the image, without the extension (and without the . )
        var path = href.substr(0, href.length - extension.length - 1);
        //we will store our new path here
        var newSrc = '';
        //get the correct path, depending on the size of the image
        if($(this).width() < 150){
            newSrc = path + '-icon.' + extension;
        }
        if($(this).width() < 350){
            newSrc = path + '-thumb.' + extension;
        }
        if($(this).width() > 350){
            newSrc = path + '-full.' + extension;
        }
        //give our image the new image path, to either an icon, thumb or full image
        $(this).attr('src', newSrc);
    }
});