我需要在动态更改的元素中触发mousedown事件。我正在制作一个图像星系,如果我点击小图像,那么大图像应该以高质量图像显示,用户可以通过以较小的div拖动大图像来查看图像。为此,只需从jquery中更改大图像容器图像的src。下面是我的代码:如何在javascript中动态更改元素中触发事件
$(document).on("click", "#thumb_img", function() {
$("#loading").show();
var smallimg = $(this).attr("src");
var img = new Image();
img.src = smallimg.replace('thumbnail/', 'images/');
img.onload = function() {
$(".large-img").prop("src", this.src);
$("#loading").hide();
};
$("img.large-img").css({
width: "500px",
height: "100%",
position: "unset"
});
});
上面的代码更改在单击小的图像时,大图片的src和下面的代码是使产生的大图像上拖动。
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
// alert("ASdf");
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('large-img').onmousedown = function() {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
此代码在页面首次加载时工作正常。然后当我点击另一个小图像时,它不起作用。
EDITED
我曾在JSFIDDLE提到我的代码。当页面加载到大图像容器中时,您可以看到图像可拖动,但是当您单击其他缩略图并尝试在大图像容器中拖动图像时,拖动事件不会触发。
可以提供我在的jsfiddle提到http://jsfiddle.net/ –
你的代码的样本。请看看。 – user254153