我想根据屏幕分辨率调用两个不同的函数。我是通过这段代码完成的,但是当用户更改宽度浏览器时,参数不会更改。有人可以帮我吗?这是代码:
function AddListItem(){
var listName="Sample"
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": new Date()
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
var itemId=data.d.Id;
var metatdata = "file";
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items("+itemId+")/AttachmentFiles/add(FileName='mycustom.txt')",
type: "POST",
contentType: "application/json;odata=verbose",
data: metatdata,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert("success: " + JSON.stringify(data));
},
error: function (data) {
alert("Error");
}
});
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
答案 0 :(得分:1)
将您的侦听器分配包装到一个函数中(这也会删除旧的侦听器)。然后在初始化时先调用此函数,然后再进行大小调整。
var width=document.body.clientWidth;
var srcBtn = document.getElementById('srcBtn');
function onresize(e) {
width = document.body.clientWidth;
console.log("width 1 is "+ width);
setListeners();
}
window.addEventListener("resize", onresize);
console.log("width is "+ width);
setListeners();
function setListeners(){
if(width>490){
srcBtn.removeEventListener("click", divSearch);
srcBtn.addEventListener("click", open);
// cls.addEventListener("click", closeBanner);
}else{
srcBtn.removeEventListener("click", open);
srcBtn.addEventListener("click", divSearch);
}
}
function open () {
console.log('open');
}
function divSearch () {
console.log('divSearch');
}
<button id="srcBtn">click me</button>
答案 1 :(得分:1)
在我看来,您真的不需要resize
。
您只需在onClick
方法中添加文档宽度测试:
function isWide() {return document.body.clientWidth > 787}
srcBtn.addEventListener("click", function(e) {
if( isWide() ) { open(e) } else { divSearch(e) }
});
cls.addEventListener("click", function(e) {
if( isWide() ) { open(e) }
});
答案 2 :(得分:0)
您还需要在事件内使用clientWidth
:
width = document.body.clientWidth;
var width = document.body.clientWidth;
function onresize(e) {
width = document.body.clientWidth;
console.log("width 1 is " + width)
}
window.addEventListener("resize", onresize);
console.log("width is " + width)