[英]Disable jQuery Based on Screen Size
如果屏幕尺寸< 601px
我想禁用以下JavaScript:
$(function() {
function rotate() {
$('#homemaincontent div').last().fadeOut(2000, function() {
$(this).insertBefore($('#homemaincontent div').first()).show();
});
}
setInterval(function() {
rotate();
}, 7000);
});
我找到了以下頁面,似乎是個不錯的答案,但我無法正常工作:
如果要檢測瀏覽器視口:
if($( window ).width() > 601){
// function
}
如果要檢測HTML文檔的寬度,請執行以下操作:
if($( document ).width() > 601){
// function
}
根據您對另一個答案的評論,您可以添加靜態圖像,如下所示:
$(function() {
function rotate() {
$('#homemaincontent div').last().fadeOut(2000, function() {
$(this).insertBefore($('#homemaincontent div').first()).show();
});
}
setInterval(function() {
if($( window ).width() > 601){
rotate();
} else {
var staticIMG = document.getElementById('staticIMG');
if (typeof(staticIMG) != 'undefined' && staticIMG != null){
return false;
} else {
$("<img id='staticIMG' src='your/static/image.png'>").insertBefore($('#homemaincontent div').first()).show();
}
}
}, 7000);
});
包括以下jQuery插件:
/*! viewportSize | Author: Tyson Matanich, 2013 | License: MIT */
(function(n){n.viewportSize={},n.viewportSize.getHeight=function(){return t("Height")},n.viewportSize.getWidth=function(){return t("Width")};var t=function(t){var f,o=t.toLowerCase(),e=n.document,i=e.documentElement,r,u;return n["inner"+t]===undefined?f=i["client"+t]:n["inner"+t]!=i["client"+t]?(r=e.createElement("body"),r.id="vpw-test-b",r.style.cssText="overflow:scroll",u=e.createElement("div"),u.id="vpw-test-d",u.style.cssText="position:absolute;top:-1000px",u.innerHTML="<style>@media("+o+":"+i["client"+t]+"px){body#vpw-test-b div#vpw-test-d{"+o+":7px!important}}<\/style>",r.appendChild(u),i.insertBefore(r,e.head),f=u["offset"+t]==7?i["client"+t]:n["inner"+t],i.removeChild(r)):f=n["inner"+t],f}})(this);
並像這樣使用它:
if (viewportSize.getWidth() > 600) {
//your function goes here
}
$(function() {
function rotate() {
$('#homemaincontent div').last().fadeOut(2000, function() {
$(this).insertBefore($('#homemaincontent div').first()).show();
});
}
setInterval(function() {
if(Math.max(document.documentElement.clientWidth, window.innerWidth || 0) > 601)
rotate();
}, 7000);
});
因此,現在每次調用Rotate時,它將首先檢查視口寬度是否大於601,如果大於601,它將執行該功能。
如果您不想針對響應行為進行調整,則只需將if語句放在$(function(){ insert if () run rest of code else do nothing}
開頭處$(function(){ insert if () run rest of code else do nothing}
,它就只會在腳本運行時計算一次首次
編輯在評論中回答關於您的第二個問題
創建一個staticImageX css類和一個DynamicImageX類,它們將具有所需的CSS,例如位置,寬度,頂部等。使用jquery和以上表達式再次針對寬度進行測試,並運行jquery代碼以在同一圖像容器上調整該類將intervan作為您的旋轉功能
if(width > 601)
$('#imageContainer').addClass('DynamicImageX').removeClass('staticImageX')
else
$('#imageContainer').addClass('staticImageX').removeClass('DynamicImageX')**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.