我正在尝试使用 jquery ui 位置插件将一个框放置在浏览器的右上角屏幕上,
$('.container').position({
my : 'right top',
at : 'right top',
of : 'body'
});
这可以正常工作并显示在右上角。但我喜欢在盒子和右侧屏幕边缘之间留出一些空间。因此,我向容器添加了 margin-right
位置。立刻,盒子从右上角移到了左上角。
骗子代码是 here .
为什么 margin 属性会影响容器的绝对坐标?
最佳答案
设置容器的边距将导致 jquery-ui 错误地计算元素的位置,但是您可以使用位置函数本身来执行此操作:
at : 'right-10px top'
除此之外,为了确保jquery将元素定位在正确的位置,定位之前内容应该位于元素内部。
在此示例中,您有 2 个按钮。第一个按钮将在右 Angular 放置一个框,而第二个按钮将在右 Angular 10px 处放置一个框。
$('.myButton1').click(function(){
console.log('adding new element into the div container')
$('.container1').append('<div class="noti-msg">this is a long small notification message... this width will fall down to the next level</div>');
$('.container1').position({
my : 'right top',
at : 'right top',
of : 'body'
});
});
$('.myButton2').click(function(){
console.log('adding new element into the div container')
$('.container2').append('<div class="noti-msg">this is a long small notification message... this width will fall down to the next level</div>');
$('.container2').position({
my : 'right top',
at : 'right-10px top',
of : 'body'
});
});
.container1, .container2 {
width: 300px;
background-color: #c3c3c3;
justify-content: center;
text-align: center;
opacity: 0.9;
}
.container2 {
background: red;
}
.noti-msg{
padding: 5px;
box-sizing: border-box;
width: 250px;
}
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.css' />
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.2.0" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/external/jquery/jquery.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.js'></script>
<button class="myButton1">my button 1...</button>
<button class="myButton2">my button 2...</button>
<br/>
<div class="container1">
</div>
<div class="container2">
</div>
关于Jquery UI 位置插件不适用于 margin 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38979489/