我想要做的是根据屏幕大小将全局变量点类型设置为“mobile”或“desktop”。Javascript,获取全局变量属性
var userScreen = {}
if (screen is small){
userScreen.type === 'mobile'
}
else {
userScreen.type === 'desktop'
}
一切工作在同一个文件内,但我有得到userScreen.type问题在其他JavaScript文件可用。
屏幕size.js:
$(document).ready(function(){
var userScreen = {};
var resizeTimer;
$(window).on('resize load', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
var windowWidth = $(window).width();
if ($('body').height() < $(document).height()) {
var windowWidth = windowWidth + 15;
}
if (windowWidth < 768){
userScreen.type = 'mobile';
}
else{
userScreen.type = 'desktop';
}
}, 250);
});
另一-JS文件
$(document).ready(function(userScreen){
console.log(userScreen.type);
});
控制台登录 “userScreen.type” 的结果:
function(obj) {
if (obj == null) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ t…
负载订购:
- 屏幕size.js
- 另一-JS-file.js
感谢
编辑
想说谢谢你大家的响应。最终的答案
所以我创建了一个IIFE只设置window.userScreen
对象
GET-用户screen.js
window.userScreen = {};
function getScreenSize(){
var windowWidth = $(window).width();
if ($('body').height() < $(document).height()) {
var windowWidth = windowWidth + 15;
}
if (windowWidth < 768){
userScreen.type = 'mobile';
}
else{
userScreen.type = 'desktop';
}
console.log(userScreen.type);
}
(function(){
getScreenSize();
}());
这提供了全局变量来就像我想和消除超时问题引起了。一切都按预期工作。
再次感谢
的userScreen不是一个全局变量。它存在于$(document).ready作用域中。 –