加载侧边栏.php基于使用 jQuery 的窗口大小



我正在尝试根据窗口大小加载我的侧边栏(侧边栏.php(。无论窗口大小如何,原始代码都会加载侧边栏。它工作正常,但我需要更改它,以便仅在窗口大于特定宽度时才加载侧边栏。这是原文:

<?php include("sidebar.php"); ?>

我尝试使用 jQuery 仅在窗口足够大以显示它时才完成加载。#sidebarcontainer 是所有侧边栏内容所在的主div。这是我尝试过的:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if($(window).width() > 665){
$("#sidebarcontainer").load("sidebar.php");
}
});
</script>

这是行不通的。侧边栏根本不显示在任何大小的窗口中。

而且我认为我还需要一个 else 语句,如果它不大于 665,则不要加载?

只需尝试以下代码100% 工作并经过测试:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Load demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>Response:</b>
<div id="sidebarcontainer"></div>
<script>
$(window).load(function(){
if($(window).width() > 665){
$( "#sidebarcontainer" ).load( "register.php", function( response, status, xhr ) {
if ( status == "success" ) {
$('#sidebarcontainer').show();
}
if ( status == "error" ) {
//var msg = "Sorry but there was an error: ";
//$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
$('#sidebarcontainer').hide();
}
});
}
else{
$('#sidebarcontainer').remove();
}
});
</script>
</body>
</html>

最新更新