Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中动态更改的元素中触发事件_Javascript_Html_Css_Image - Fatal编程技术网

如何在javascript中动态更改的元素中触发事件

如何在javascript中动态更改的元素中触发事件,javascript,html,css,image,Javascript,Html,Css,Image,我需要在动态更改的元素中触发mousedown事件。我正在制作一个图像galary,如果我点击小图像,那么大图像应该显示高质量的图像,用户可以通过在小div中拖动大图像来查看图像。因为这只是从jquery更改大图像容器图像的src。下面是我的代码: $(document).on("click", "#thumb_img", function () { $("#loading").show(); var

我需要在动态更改的元素中触发mousedown事件。我正在制作一个图像galary,如果我点击小图像,那么大图像应该显示高质量的图像,用户可以通过在小div中拖动大图像来查看图像。因为这只是从jquery更改大图像容器图像的src。下面是我的代码:

 $(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;
当页面第一次加载时,此代码工作正常。然后,当我点击另一个小图片,它不工作

编辑


我在信中提到了我的代码。当页面加载到大型图像容器中时,您可以看到图像是可拖动的,但当您单击其他缩略图并尝试在大型图像容器中拖动图像时,则不会触发拖动事件。

从您的描述和代码来看,您似乎有多个id为
thumb\img的元素,但是ID必须是唯一的。

位置:“unset”
是问题所在。删除它,问题就消失了


您能否提供我在JSFIDLE中提到的代码示例。请看一看。这是我的错误。我纠正了它。但这不是解决方案的问题。