【问题标题】:Disable javascript file based on media query portrait mode禁用基于媒体查询纵向模式的javascript文件
【发布时间】:2015-03-04 21:48:36
【问题描述】:
我想在 ipad 纵向模式下从一个 javascript 文件切换到另一个 javascript 文件(这样我就可以在纵向模式下从水平滚动切换到垂直滚动)。
我发现了类似的东西:http://wicky.nillia.ms/enquire.js/
但我找不到任何东西来禁用/启用基于此查询的 javascript 文件:
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait)
【问题讨论】:
标签:
javascript
media-queries
horizontal-scrolling
landscape-portrait
【解决方案1】:
我认为您不需要 javascript 来执行此操作。这是jsfiddle example,下面是css:
@media only screen and (min-width : 768px) and (max-width : 1024px)
{
.container {
overflow-y: scroll;
}
}
【解决方案2】:
我相信 CSS 媒体查询用于样式和响应式设计。
我会使用 javascript 本身来动态更改包含的脚本文件。
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml举个例子
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
removejscssfile("somescript.js", "js") //删除页面上所有出现的"somescript.js"
removejscssfile("somestyle.css", "css") //删除页面上所有出现的“somestyle.css”
我希望这有助于为您指明正确的方向。
【解决方案3】:
我通过在外部 javascript 文件本身的 javascript 中使用媒体查询使其工作(它只是导致垂直/水平变化的一行):
var mq = window.matchMedia('only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait)');if(mq.matches) {$(document).ready(function () {$.localScroll.defaults.axis = 'y'; $.localScroll(); });} else {$(document).ready(function () {$.localScroll.defaults.axis = 'x'; $.localScroll(); });}
更多信息:http://krasimirtsonev.com/blog/article/Using-media-queries-in-JavaScript-AbsurdJS-edition
虽然我必须刷新页面才能工作,但我还没有在真正的 ipad 上测试过..