1

I am making a rich-text editor and I am trying to place a delete button div at top-left corner of an image dynamically inserted by javascript. Thus I must determine the position of the div at run-time. However, I couldn't make it exactly located at the top-left corner. Here is my code:

function showDeleteButton(image) {
    var rect = image.getBoundingClientRect();
    var top = rect.top + $(document).scrollTop();
    var left = rect.left + $(document).scrollLeft();
    var deleteButton = $(".delete_button")[0];
    deleteButton.style.visibility = 'visible';
    deleteButton.style.top = top + "px";
    deleteButton.style.left = left + "px";
}

Any help would be greatly appreciated!

4

2 回答 2

1

您可以将删除按钮作为元素的直接子body元素。然后您可以测量悬停图像的偏移量并将按钮重新定位到其左上角。

CSS

.delete_button {
    position:absolute;
    display:none;
}

jQuery

$(function() {
    var deleteButton = $(".delete_button");
    var hovered_image = false;
    $('img').mouseenter(function(e) {
        hovered_image = this;
        deleteButton.show();
        var img = $(this);
        var offset = img.offset();
        deleteButton.css({
            top: offset.top + 'px',
            left: offset.left + 'px'
        });
    }).mouseleave(function(e) {
        if (e.relatedTarget === deleteButton[0]) {
            return;
        }
        deleteButton.hide();
        hovered_image = false;
    });
    deleteButton.mouseleave(function(e){
        if (e.relatedTarget === hovered_image) {
            return;
        }
        deleteButton.hide();
        hovered_image = false;
    });
    deleteButton.click(function(e){
        hovered_image.parentNode.removeChild(hovered_image);
        deleteButton.hide();
    });
});

JSFiddle: http: //jsfiddle.net/djuVT/ -上述解决方案与 jQuery 的.offset()方法和position:absolute.

JSFiddle: http: //jsfiddle.net/djuVT/1/ -使用 Javascript 的.getBoundingClientRect()方法和position:fixed;CSS的替代解决方案

于 2013-08-17T08:31:37.767 回答
1

html

<div>
    <div id="delete_button"></div>
    <img src"foo.png" />
</div>

和CSS

#delete_button{
    position:absolute;
    top:0;
    left:0
    z-index:1;
}
于 2013-08-17T07:18:52.230 回答