我正在尝试对定位为absolute
的元素使用jQuery wrap
函数。以下是我的代码。
单击子元素时,我用另一个 div 包装了相同的子元素,但它不起作用。相反,包装器元素出现在屏幕顶部。如何操作 css
或 js
来包装子元素。
$(document).ready(function() {
$("#child").click(function() {
$(this).wrap("<div class='wrapper'></div>")
});
});
#container {
position: relative;
height: 500px;
width: 600px;
background: #ccc
}
#child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: #444;
border: 2px solid red;
height: 200px;
width: 200px;
}
.wrapper {
border: 1px dashed green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="child">
</div>
</div>
最佳答案
只需更新包装器
类
$(document).ready(function() {
$("#child").click(function() {
$(this).wrap("<div class='wrapper'></div>")
});
});
#container {
position: relative;
height: 500px;
width: 600px;
background: #ccc
}
#child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: #444;
border: 2px solid red;
height: 200px;
width: 200px;
}
.wrapper {
border: 1px dashed green;
height: 200px;
width: 200px;
position:absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="container">
<div id="child">
</div>
</div>
关于javascript - 使用具有绝对放置元素的 Jquery 包装函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37362311/