我正在尝试创建一个响应式网站,并希望根据屏幕宽度(开始时和调整大小时)交换位置两个div。
我做了一些研究并尝试了一些选择,但没有运气。我是JQuery和JS的新手,所以任何帮助都会非常感激。
HTML
<div id="div1">facebook</div>
<br/>
<div id="div2"><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY"/></div>
jquery的
$(document).ready(function(){
div1 = $('#div1');
div2 = $('#div2');
tdiv1 = div1.clone();
tdiv2 = div2.clone();
.resize()
});
$(window).resize(function() { //Fires when window is resized
if($(window).width() < 800){
div1.replaceWith(tdiv2);
div2.replaceWith(tdiv1);}
else{
div1.replaceWith(tdiv1);
div2.replaceWith(tdiv2);}
});
答案 0 :(得分:3)
实现这一目标的最简单方法是将其放在包装器中,并将append()
和prepend()
包装在div中:
<强> HTML 强>
<div class="wrapper">
<div id="div1">facebook</div>
<br/>
<div id="div2">
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY" />
</div>
</div>
<强> Jquery的强>
$(window).on('load resize', function() { //Fires when window is loaded or resized
var div1 = $('#div1');
var div2 = $('#div2');
var wrapper = $('.wrapper');
if ($(window).width() < 800) {
wrapper.prepend(div1).append(div2); // move div 1 to start & div2 to end
} else {
wrapper.prepend(div2).append(div1); // move div 2 to start & div 1 to end
}
});
如果你想以不同的方式写它:
$(window).on('load resize', function() { //Fires when window is loaded or resized
var windowWidth = $(window).width(),
div1 = $('#div1'),
div2 = $('#div2'),
first = windowWidth < 800 ? div1 : div2,
last = windowWidth >= 800 ? div2 : div1;
$('.wrapper').prepend(first).append(last);
});
答案 1 :(得分:1)
试试这个:
<script type="text/javascript">
var run = false;
$(window).on("resize",function(){
if($(window).width()<800 && !run) {
$("#div2").remove();
$('<div id=div2><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY"/></div>').insertBefore($("#div1"));
run = !run;
}
else if($(window).width() >= 800 && run){
$("#div1").remove();
$('<div id=div1>facebook</div>').insertBefore($("#div2"));
run = !run;
}
})
</script>
最终代码:
注意:想要运行代码段时,请点击整页。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="div1">facebook</div>
<br/>
<div id="div2"><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY"/></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
var run = false;
$(window).on("resize",function(){
if($(window).width()<800 && !run) {
$("#div2").remove();
$('<div id=div2><img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSFjZm7TgmvK8lEfSkzytyCuE1ZDE1WdexDyj7eRLSPHfexJQruR8uIGfY"/></div>').insertBefore($("#div1"));
run = !run;
}
else if($(window).width() >= 800 && run){
$("#div1").remove();
$('<div id=div1>facebook</div>').insertBefore($("#div2"));
run = !run;
}
})
</script>
</body>
</html>
&#13;
注意:想要运行代码段时,请点击整页。