Jquery UI 位置插件不适用于 margin 属性

标签 jquery html css position

我正在尝试使用 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/

相关文章:

javascript - 从 JavaScript 驱动的表单获取文本字段值并将这些值附加到 div

javascript - 如何将图像数组插入到 swipebox 画廊中?

html - 带有div的ie7 css在TD中右对齐

javascript - 问题 - AngularJS 未捕获错误 : [$injector:modulerr]

html - 悬停期间的淡入淡出效果 - border-radius 不起作用

html - 边框样式在 Internet Explorer 11 中不起作用

javascript - 如何更改标签、ID 或类无法选择的文本?

jquery - Superfish 在 Concrete5 编辑模式中将悬停类添加到父项

javascript - 如何选择optgroup

jquery - CSS 中的响应式可滚动选项卡式导航