简体   繁体   English

php if-屏幕宽度-加载js

[英]php if - screen width - load js

I'm new to php. 我是php新手。 I have a doubt, don't know if this can be done, or if it should be done in another way or what. 我有一个疑问,不知道这是否可以完成,或者是否应该以其他方式完成。 I want to load a JS only if the screen size is higher than x size. 我只想在屏幕尺寸大于x尺寸时加载JS。

I wrote this but the JS is not being loaded (in fact I want to load a couple of JS): 我写了这个,但是没有加载JS(实际上我想加载几个JS):

<script language="javascript">
if (screen.width > 549) {
    <script src='js/jquery-1.8.1.min.js' type='text/javascript'></script>
}

best regards! 最好的祝福!

php cannot detect a clients screen width/height, that all would have to be done client side. php无法检测到客户端屏幕的宽度/高度,因此必须在客户端完成所有操作。

function addScript(src){
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.src = src;
   document.head.appendChild(script);
} 

if(screen.width > 549){
    addScript("js/jquery-1.8.1.min.js");
    addScript("js/someOtherScript.js");
}

It's cleaner to detect the screen width in JavaScript. 在JavaScript中检测屏幕宽度更加干净。 Also remember the screensize can change in a session. 还请记住,屏幕大小可以在会话中更改。 For example when a user resizes his screen. 例如,当用户调整屏幕大小时。

Use this in your JavaScript file: 在您的JavaScript文件中使用此命令:

var width = document.body.clientWidth;
if(width > 549) {

} else if(width < 300) {

} else {

}

You cannot determine a clients' browser window size before a client has received a page with PHP. 在客户端收到带有PHP的页面之前,您无法确定客户端的浏览器窗口大小。

Technically you could load a page, get javascript to send back the window size and then store it in the session for that user, but I don't really see the point. 从技术上讲,您可以加载一个页面,获取javascript以发送回窗口大小,然后将其存储在该用户的会话中,但是我没有真正的意义。 You're better off either always including the javascript file, or using a javascript library to conditionally add other scripts to the DOM. 您最好始终包含javascript文件,或者使用javascript库有条件地将其他脚本添加到DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM