与其依赖 jQuery,您可以通过将两个元素设置为内联元素、强制它们接触并将容器的 CSS 设置为 white-space: nowrap 来使两个元素在 CSS 中粘在一起。
HTML:
<div id="main">
<p>If the draw is popped out, and you resize the page, it breaks, because it has position:absolute</p>
<div id="clickable">
<div id="trigger">
<span>Click here - click away to hide</span>
</div><div id="pop">
<span>Now Resize Page</span>
</div>
</div>
</div>
请注意,</div><div id="pop"> 不是拼写错误。要强制触摸内联元素,您需要删除标记中的所有空格。
CSS:
#main {
width:300px;
margin:50% auto;
margin-top:0;
margin-bottom:0;
background-color:#EEE;
padding:10px;
}
#clickable { white-space: nowrap; }
#trigger {
background-color: #FFF;
width: 100%;
border: 4px solid #ddd;
display: inline-block; }
#trigger span { margin: 5px; display: block; }
#pop {
background-color: #333;
color: #EEE;
height: 38px;
opacity: 0;
display: none; }
#pop span {
margin: 10px;
display: block; }
JS:
$('#trigger').click(function(event) {
event.stopPropagation();
var width = $(this).outerWidth();
var offset = $(this).offset();
var top = (offset.top+4)+'px';
var left = (offset.left+width)+'px';
$('#pop').css({
'top' : top,
'left' : left,
'display' : 'inline-block',
'opacity' : 0,
'width' : 0
}).animate({
'width' : '140px',
'opacity' : 1
});
});
$('html').click(function(event) {
if (!($(event.target).closest('#pop').length)) {
$('#pop').animate({'width':0,'opacity':0},500,
function() {
$(this).hide();
});
}
});
预览:http://jsfiddle.net/Wexcode/4kg2W/3/