4

我在使用 css 调整大小以保持一致性的图像上使用Jcrop

JS

<script type="text/javascript">
    $(window).load(function() {
        //invoke Jcrop API and set options
        var api = $.Jcrop('#image', { onSelect: storeCoords, trueSize: [w, h] });
        api.disable(); //disable until ready to use

        //enable the Jcrop on crop button click
        $('#crop').click(function() {
            api.enable();
        });
    });
    function storeCoords(c) {
    $('#X').val(c.x);
    $('#Y').val(c.y);
    $('#W').val(c.w);
    $('#H').val(c.h);
    };
</script>

HTML

<body>
    <img src="/path/to/image.jpg" id="image" class="img_class" alt="" />
     <br />
     <span id="crop" class="button">Crop Photo</span>
     <span id="#X" class="hidden"></span>
     <span id="#Y" class="hidden"></span>
     <span id="#W" class="hidden"></span>
     <span id="#H" class="hidden"></span>
</body>

CSS

body { font-size: 13px; width: 500px; height: 500px; }
.image { width: 200px; height: 300px; }
.hidden { display: none; }

我需要将hw变量设置为实际图像的大小。我尝试使用.clone()操纵器制作图像的副本,然后从克隆中删除类以获取大小,但它将变量设置为零。

var pic = $('#image').clone();
pic.removeClass('image');
var h = pic.height();
var w = pic.width();

如果我将图像附加到页面中的元素,它会起作用,但这些是更大的图像,如果有更好的方法,我不希望将它们作为隐藏图像加载。同样删除类,设置变量,然后重新添加类会产生零星的结果。

我希望有一些类似的东西:

$('#image').removeClass('image', function() {
    h = $(this).height();
    w = $(this).width();
}).addClass('image');

但是该removeClass功能不能那样工作:P

4

2 回答 2

4

尝试隐藏图像,然后获取尺寸,然后显示它:

var $img = $("#image");
$img.hide().removeClass("image");
var width = $img.width();
var height = $img.height();
$img.addClass("image").show();

这应该会删除您在添加和删除类时可能会看到的任何奇怪行为。

于 2011-01-08T14:08:33.867 回答
1

也许您可以克隆图像(不应该对网络造成极大的痛苦,因为它应该被缓存),并获得克隆图像的大小:

$newImg = $("#image").clone();
$newImg.css("display", "none").removeClass("image").appendTo("body");
var width = $newImg.width(), height = $newImg.height();
$newImg.remove();

祝你好运!

于 2011-01-08T14:13:09.357 回答