【问题标题】:jQuery how to scale image with markersjQuery如何使用标记缩放图像
【发布时间】:2018-06-01 13:44:13
【问题描述】:

我有这个:

<style>
#pic_wrapper{
    display: block;
    position: relative;
    padding: 0;
}
#selected_picture img {
    width: 100%;
    height: auto;
}
.pin {
    display: none; 
    position: absolute; 
    height: 50px;
    width: 50px;
    padding: 0;
    margin: 0;
}
</style>

<div id="pic_wrapper">
    <div id="selected_picture">
        <img src="map.png" />
    </div>
</div>

并将标记附加到图像:

<script type="text/javascript" charset="UTF-8">
$(function(){
    $('#selected_picture').on('click', function(e){
        offset = $('#selected_picture').offset();
        x = e.pageX - offset.left - 25;
        y = e.pageY - offset.top - 25;
        var pin = $('<div class="pin"><img class="pin-img" src="pin.png" /></div>');
        pin.uniqueId();
        $('#pic_wrapper').append(pin);
        pin.css('left', x).css('top', y).show();

我需要将#selected_picture 连同所有引脚一起缩放,以使它们保持在相同的相对位置。

我在 div 中找到了这个文本示例:https://codepen.io/chriscoyier/pen/VvRoWy

但我可以弄清楚如何将这种方法应用于我的可调整大小的图片,上面有绝对定位的图钉。

感谢您的帮助。

【问题讨论】:

  • 用 % 值代替引脚。
  • 你的意思是'e.pageX - offset.left - 25' 应该是屏幕宽度的百分比吗?
  • 并且引脚是'位置:绝对' - 它们不会随着调整大小而移动
  • 没关系,对topleft 位置使用% 值。
  • 另请注意,您不会在任何时候将 pin 元素添加到 DOM 中

标签: jquery scale image-resizing


【解决方案1】:

这里的想法很简单,您可以计算图钉相对于您单击的图像的位置百分比。当您使用 position: absolute 和百分比 top/left 值时,它会告诉浏览器将元素定位在 relative parent 宽度/高度的百分比处,因此一旦父尺寸发生变化,您的位置也会自动更新。

$(function(){
    $('#selected_picture').on('click', function(e){
        x = ((e.offsetX) / $(this).width()) * 100 + "%";
        y = ((e.offsetY) / $(this).height()) * 100 + "%";
        var pin = $('<div class="pin"></div>');
        $('#pic_wrapper').append(pin);
        pin.css('left', x).css('top', y).show();
    })
});
#pic_wrapper{
    display: block;
    position: relative;
    padding: 0;
}
#selected_picture .map {
    display: block;
    background: green;
    width: 100%;
    height: 250px;
}
.pin {
    display: none; 
    position: absolute; 
    height: 50px;
    width: 50px;
    transform: translate(-50%, -50%);
    padding: 0;
    margin: 0;
    background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pic_wrapper">
    <div id="selected_picture">
        <div class="map"></div>
    </div>
</div>

【讨论】:

  • 这样的工作,但位置随缩放而变化。我需要针脚相对于图像保持在完全相同的位置。我的意思是在图像的同一位置
  • @linuxoid 稍微修改了代码。确保您的相对父级 (#pic_wrapper) 与图像大小相同,否则定位将不正确。
  • 它们应该在您调整图像大小时移动,因为它们被中心“附加”。所以看起来他们好像在移动,但中心会在同一个点上。实际上,您可以相当容易地对其进行测试 - 使引脚更小(例如 5px 左右),您会发现它们位于相同的位置。
  • 是的,你是对的。非常感谢您的帮助。他们现在都可以正确移动。但我发现,如果我点击任何一个,它们就会从移动中分离(引脚是可拖动的)并且总是停留在同一个位置。我现在如何计算他们的新坐标?什么是“移动”?
  • @linuxoid 你确定你的其他代码不会导致这种行为吗?因为在我给onclick 处理程序的代码中甚至没有为pins 触发(因为它们在#selected_picture 元素之外)
猜你喜欢
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 2022-07-05
  • 2022-01-22
  • 1970-01-01
  • 2013-05-24
相关资源
最近更新 更多