jquery调整大小,保持评论相对于图像的位置

时间:2014-10-09 22:39:21

标签: jquery css resize position

jsFiddle

我创建了一个脚本,允许用户在图像上发表评论。 img是响应式的,但img之上的评论并没有。当我调整大小时,评论保留在原来的顶部和左侧位置,我无法让他们保持各自的位置。我上传了一个jquery小提琴给你看。我真的可以帮到你了!

var oldHeight = $('#proofNow').height(),
    oldWidth = $('#proofNow').width();

$(window).resize(function() {
    var parent = $('#proofNow'),
        parentWidth = parent.width(),
        parentHeight = parent.height();

    $("img.TDot").each(function(){
        var top = parseInt($(this).css("top")),
            left = parseInt($(this).css("left")),
            topRatio = oldHeight / top,
            leftRatio = oldWidth / left,
            newTop = parentHeight / topRatio,
            newLeft = parentWidth / leftRatio;

        //console.log('top: ' + top + ', left: ' + left);
        $(this).css("top", newTop);
        $(this).css("left",newLeft);
    });

    console.log(parent.width());
});

我猜我的数学错了,但我仍然想不通。我需要能够双向进行

1 个答案:

答案 0 :(得分:0)

我很困惑为什么你需要Javascript呢?什么阻止你让浏览器做艰苦的工作,并使用CSS / Html。

Css Block

div {
    position: relative;
    left: 0px;
    top: 0px;
    width="60%"
}

Html Block

<div>
   <div name="comments"> ... </div>
   <img src="..." />
</div>