开发者

add image on top of div css + jQuery

I have a div that is styled like a box. It is dragged using jQuery UI. When it is dragged I would like to add an image to the top of the box. The image should be overlapping the box, so background is out of the开发者_StackOverflow社区 question.

  1. How do I add such image? Do I use append?

  2. The draggable box has a dynamic z-index set by jQuery UI. How do I make sure that appended image is at least +1 to be on top?

add image on top of div css + jQuery


Add the image with prepend, and position it absolutely:

var $mainBox = $('#main-box')
                    .prepend('<img class="centered" src="..." />')
                    .css('position', 'relative'),

    $img = $mainBox.find('.centered');

$img.css({
    position: 'absolute',
    top: '-20px', // change this to whatever you want
    left: ( $mainBox.width() - $img.width() ) / 2
});

A better approach would be to have the img there all along, and just show/hide it when dragging. That way, you can keep your CSS where it belongs, and you won't have to shuffle elements in and out of the DOM.


You're going to have problems with losing focus the second you place another element over your draggable. You need to change your flow so the draggable element has the box inside it.

<div class="draggable-item">
 <div class="show-on-drag"></div>
 <div class="box"></div>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜