gpt4 book ai didi

javascript - jQuery 在调整大小时移动元素

转载 作者:行者123 更新时间:2023-11-28 06:12:05 24 4
gpt4 key购买 nike

我正在努力发现这段 jQuery 代码的问题所在。我正在尝试将几个元素从一个 div 移动到另一个。取决于屏幕的宽度。该代码在页面加载时有效,但在我调整大小时无效。

var domWidth = $(window).width();

//Move around page elements
function moveElements() {
var pageTitle = $('.page-title'),
actionAlert = $('.action-alert'),
banner = $("#banner>.container"),
header = $("header>.container"),
mainContent = $(".main-content");

if (domWidth < 1024) {
pageTitle.prependTo(mainContent);
actionAlert.appendTo(header);
} else {
pageTitle.appendTo(banner);
actionAlert.prependTo(banner);
}
}

$(document).ready(function() {
moveElements();
$(window).resize(function() {
moveElements();
});

});

最佳答案

 //Move around page elements
function moveElements() {
var domWidth = $(window).width();
var pageTitle = $('.page-title'),
actionAlert = $('.action-alert'),
banner = $("#banner >.container"),
header = $("#header >.container"),
mainContent = $(".main-content");
if (domWidth < 1024) {
pageTitle.prependTo(mainContent);
actionAlert.appendTo(header);
} else {
pageTitle.appendTo(banner);
actionAlert.prependTo(banner);
}
}

$(document).ready(function() {
moveElements();
$(window).resize(function() {
moveElements();
});

});

Some Serious edits are made to your code .
the errors in your code are

  1. 主要是将 var domWidth =$(window).width(); 放在函数之外。//它应该在函数内,因为每次函数工作时你都需要找到宽度。
  2. 您错过了在 header = $("header>.container")
  3. 中添加 #

For the sake of checking I made a working demo in https://jsfiddle.net/8m0d1462/ (reduced the width to 400 for the sake of checking)

关于javascript - jQuery 在调整大小时移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com