将克隆元素绝对定位在 jQuery 中
Absolutely Position a Cloned Element in jQuery
我正在尝试用 jQuery 绝对定位克隆的 div。当我使用 .css() 方法将 CSS 添加到克隆元素时,它只会移动文本(即使我将所有父元素的 CSS 复制到该对象中。
我这里有一个 fiddle : https://jsfiddle.net/emilychews/xuup6va1/3/
如果您单击蓝色 div,它会创建一个克隆。
为了快速参考,代码是:
$('#testdiv').click(function() {
$(this).clone()
.insertAfter('#testdiv');
});
#wrapper {
width: 100%;
height: 100%;
}
#testdiv {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 20px;
box-sizing: border-box;
padding: 10px;
background-color: blue;
color: white;
height: 350px;
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="testdiv">
<h1>I am a div</h1>
<p>with a blue background</p>
</div>
</div>
如果我这样做对我来说效果很好:
$('#testdiv').click(function() {
$( this ).clone()
.insertAfter('#testdiv')
.css({
position: 'absolute',
top: 0
});
});
但请注意,您的元素有一个 ID。因此,如果您克隆 id,则会创建无效标记。
我正在尝试用 jQuery 绝对定位克隆的 div。当我使用 .css() 方法将 CSS 添加到克隆元素时,它只会移动文本(即使我将所有父元素的 CSS 复制到该对象中。
我这里有一个 fiddle : https://jsfiddle.net/emilychews/xuup6va1/3/
如果您单击蓝色 div,它会创建一个克隆。
为了快速参考,代码是:
$('#testdiv').click(function() {
$(this).clone()
.insertAfter('#testdiv');
});
#wrapper {
width: 100%;
height: 100%;
}
#testdiv {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 20px;
box-sizing: border-box;
padding: 10px;
background-color: blue;
color: white;
height: 350px;
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div id="testdiv">
<h1>I am a div</h1>
<p>with a blue background</p>
</div>
</div>
如果我这样做对我来说效果很好:
$('#testdiv').click(function() {
$( this ).clone()
.insertAfter('#testdiv')
.css({
position: 'absolute',
top: 0
});
});
但请注意,您的元素有一个 ID。因此,如果您克隆 id,则会创建无效标记。