我的html的初始结构如下所示:
<div class="geniuses">
<div class="one-first">
</div>
<div class="one-second">
</div>
<div class="one-third">
</div><!-- one third-->
</div>
我怎样才能将班级与班级分开一秒钟,然后将班级放在班级前一班?
目前我的jquery看起来像这样:
$(window).resize(function resize(){
if($(window).width() < 1070){
$('.one-second').detach();
$('.one-first').before($('.one-second'));
}
}).trigger('resize');
现在我只能分离,但我很难将内容放回到我想要的位置,而且当我将屏幕大于1070像素时,div也不会显示回来。
答案 0 :(得分:1)
在detach
div
之后,您可以将其存储到变量或jQuery对象中,然后将其附加回来(appendTo
,prependTo
)。
让我们说这是我们的HTML -
<body>
<div class="geniuses">
<div class="one-first">A
</div>
<div class="one-second">P
</div>
<div class="one-third">Z
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
JS:
$(window).resize(function resize() {
if ($(window).width() > 1070) {
// if width is more the 1070px. tweek accordingly.
var $p = $('.one-second').detach();
$p.prependTo($('.one-first'));
} else {
// To put things back into place
var $p = $('.one-second').detach();
$p.appendTo($('.one-first'));
}
});
希望它有所帮助。
答案 1 :(得分:0)
截至目前,你正在分离它永远不会附加回来。您创建了新的div
并使用.before()
将字符串文字.one-first
添加到其中。
您需要放置目标元素并使用它。注意.before()
接受要在selector
之前插入的元素或HTML字符串。
$(window).resize(function resize() {
if ($(window).width() < 1070) {
$('.one-first').before($('.one-second'));
//$('.one-second').insertBefore('.one-first');
}
}).trigger('resize');
另外,也可以使用.insertBefore()
。
.before()
和.insertBefore()
方法执行相同的任务。主要区别在于语法特定,内容和目标的放置。使用.before(),方法前面的选择器表达式是插入内容之前的容器。另一方面,对于.insertBefore()
,内容在方法之前,作为选择器表达式或动态创建的标记,并且在目标容器之前插入。
$('.one-first').before($('.one-second'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="geniuses">
<div class="one-first">
1
</div>
<div class="one-second">
2
</div>
<div class="one-third">
3
</div>
</div>
答案 2 :(得分:0)
完成@PEJK的回复是答案
$(window).resize(function resize() {
if ($(window).width() > 1070) {
// if width is more the 1070px. tweek accordingly.
var $p = $('.one-second').detach();
$p.prependTo($('.one-first'));
} else {
// To put things back into place
var $p = $('.one-second').detach();
$p.appendTo($('.one-first'));
}
}).trigger('resize');