gpt4 book ai didi

javascript - 如何在可拖动元素中使用 % 代替 px ?

转载 作者:行者123 更新时间:2023-11-28 07:01:03 28 4
gpt4 key购买 nike

我陷入困境,需要帮助。我正在用标记制作 map 。我可以添加标记等。我的主容器具有 100% 的宽度和高度。当我单击某处时,我的标记具有 % 值,例如 top: 34%;左:35%;拖动标记后新位置具有 px 值。我想保存%值。有什么想法吗?

map .js

jQuery(document).ready(function($){

// basic add

$("button#remove").click(function(){
$(".marker").remove();
});


//add with position
var map = $(".map");
var pid = 0;

function AddPoint(x, y, maps) {

// $(maps).append('<div class="marker"></div>');
var marker = $('<div class="marker ui-widget-content"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker)
$('.marker').draggable().resizable();
}
map.click(function (e) {
// var x = e.pageX - this.offsetLeft;
// var y = e.pageY - this.offsetTop;
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';

// $(this).append('<div class="marker"></div>');
AddPoint(x, y, this);
});


// drag function
$(".ui-widget-content").draggable({
drag: function( event, ui ) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
}
});

});

样式.css

.wrapper {
margin: 0 auto;
width: 100%;
min-height: 400px;
overflow: hidden;
}

.map {
width: 100%;
position: relative;
}

.map > img {
max-width: 100%;
max-height: 100%;
}
.marker {
width: 10px;
height: 10px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
position: absolute;
left: 50%;
top: 50%;
z-index: 999;
}

#mapa {
width: 30px;
height: 30px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
z-index: 999;
}

一些html代码

    <div class="wrapper">
<div class="map">
<img src="http://i.imgur.com/HtxXGR5.jpg" width="100%" height="auto" margin="15px 0;" alt="">
</div>
<button id="remove">Remove all markers</button>
</div>

最佳答案

如果你想捕获位置,在拖动结束后(每次拖动触发1次)你可以这样做:

$('.marker').draggable({
stop: function() {
var offset = $(this).offset();
var mapOffest = $('.map').offset();

var x = ((offset.left - mapOffest.left)/ ($(".map").width() / 100))+"%";
var y = ((offset.top - mapOffest.top)/ ($(".map").height() / 100))+"%";

// We need to do something with thoses vals uh?
$(this).css('left', x);
$(this).css('top', y);
// or
console.log('X:'+x + '||Y:'+y);
}
});

Fiddle here

请注意,该事件已直接在标记上设置,这可能是您的错误。

这个小计算需要处理 map 偏移,如果您的 map 是全宽/高(窗口大小),则不需要处理该偏移

如果您需要,或者更喜欢使用 drag 事件而不是 stop,这些行不会产生任何效果

$(this).css('left', x);
$(this).css('top', y);

但是您仍然能够捕获该位置,控制台值将是商品。

希望对您有帮助。

关于javascript - 如何在可拖动元素中使用 % 代替 px ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32136283/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com