重新定位相对于父级调整大小的div标签

时间:2015-11-10 17:25:10

标签: javascript jquery css

一个元素有多个子元素,子元素具有绝对定位,在调整父元素大小时,我想计算接近原始大小的子元素的坐标。

请点击fiddle1,在这里我可以点击图片并为其添加标签,在调整窗口大小时,图像会通过保留其纵横比来调整大小,计算同时重新定位标签(非常接近原始图像)地点)。问题是当我添加其他组件时,代码@ fiddle2,这会严重重新定位标签,请帮我解决这个重新定位pbm @ fiddle2!

代码:



var originalx;
var originaly;
var ratio;
var tag = "<div class='tag'>Letter</div>";

calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight) {
    ratio = [maxWidth / srcWidth, maxHeight / srcHeight];
    ratio = Math.min(ratio[0], ratio[1]);
    $('#ratio').text('ratio: '+ratio);
    return {
        width: srcWidth * ratio,
        height: srcHeight * ratio
    }};


    $(document).ready(function () {
        originalx = $('#img').width();
        originaly = $('#img').height();
        $('#currentimgwrap').click(function (e) {
            var offset = $(this).offset();
            var x = (e.pageX);
            var y = (e.pageY);
            var tagpoint = $(tag);
            var size = $('#currentimgwrap').children().size() - 1;
            $(tagpoint).attr('id', 'tag' + size);
            $('#currentimgwrap').append(tagpoint);
            $(tagpoint).css({
                left: x,
                top: y
            });
           
            $('#locations').append(
                "<div><span>"+ (size+1) +" -> <span id='location" + size + "'>"+ x + ',' + y + "</span></span></div>");

        });
        
    });

$(window).resize(function(){
		currentsize = calculateAspectRatioFit(originalx,originaly,window.innerWidth, window.innerHeight);
		$('#img').width(currentsize.width);
    	$('#img').height(currentsize.height);
    	update();
	});

update=function() {
		$('#currentimgwrap').width(currentsize.width);
		$('.tag').each(function(indx){
			var xy = $('#location'+indx).text().split(',');
			x = xy[0]*ratio;
			y = xy[1]*ratio;
			$('#tag'+indx).css({
				left:x, top:y
			});
		});
	}
&#13;
html, body {
    height: 100%;
    width: 100%;
}

.tag {
	position: absolute;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imgarea">
    <div id="currentimgwrap">
        <img id="img" src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
    </div>
    <div id="ratio">ratio: 1</div>
    <div id="locations"></div>
</div>
&#13;
&#13;
&#13;

如果我添加另一个html组件,相同的代码将失败。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Some content here causes problem :(</div>
<div id="imgarea">
    <div id="currentimgwrap">
        <img id="img" src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />
    </div>
    <div id="ratio">ratio: 1</div>
    <div id="locations"></div>
</div>

0 个答案:

没有答案