我有一个 html DIV,如下所示
<div id="mapimage" style="background-image: url('images/physical-map.jpg'); width: 500; height: 548; background-repeat: no-repeat"></div>
要在此 DIV 背景图像上添加标记,我正在执行以下操作。
$(document).ready(function () {
$('div#mapimage').mousedown(function (e) {
e.preventDefault();
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var img = $('<img>');
img.css('top', y);
img.css('left', x);
img.attr('src', 'images/red-dot.png');
img.appendTo('#mapimage');
});
这工作正常,我需要的是 - 第一次,我将在 DIV 的位置 (10,122) 添加一个标记。如果我第二次点击相同的位置,添加的标记应该从那里删除。如何做到这一点?
最佳答案
将类添加到 img
并在每次单击 map 图像时删除该类。
$(document).ready(function () {
$('div#mapimage').mousedown(function (e) {
e.preventDefault();
// remove all images
$('.remove-me').remove();
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var img = $('<img>');
img.css('top', y);
img.css('left', x);
img.attr('src', 'images/red-dot.png');
// add a class to the image
img.addClass('remove-me');
img.appendTo('#mapimage');
});
});
或者
不是每次单击 map 时都删除所有图像,而是简单地删除被单击的图像。
$(document).ready(function () {
// remove images that are clicked
$('.remove-me').on('click', function(){
$(this).remove();
});
$('div#mapimage').mousedown(function (e) {
e.preventDefault();
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var img = $('<img>');
img.css('top', y);
img.css('left', x);
img.attr('src', 'images/red-dot.png');
// add a class to the image
img.addClass('remove-me');
img.appendTo('#mapimage');
});
});
关于jquery - 使用 Jquery 在图像上添加或删除标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10361045/