用另一个脚本包装javascript

时间:2015-06-17 11:22:06

标签: javascript

我想用另一行来包装javascript函数,该行将决定脚本应该运行与否。关键是如果用户在移动设备上,则禁用主脚本。

我能解决的问题是如何让它发挥作用。

这是初始脚本

    <script>


    function init() {

        window.addEventListener('scroll', function(e){
            var distanceY = window.pageYOffset || document.documentElement.scrollTop,
                shrinkOn = 200,
                header = document.querySelector("header");
            if (distanceY > shrinkOn) {
                classie.add(header,"smaller");
            } else {
                if (classie.has(header,"smaller")) {
                    classie.remove(header,"smaller");
                }
            }

        });

            } 
    window.onload = init();

</script>

这是我想用它包装的脚本。

window.addEventListener('resize', function(){
    if(window.innerWidth > 568){
        ...execute script
    }
});

我将如何构建代码来实现这一目标?

谢谢, 托拜厄斯

3 个答案:

答案 0 :(得分:0)

我建议使用enquire.js

function init() {
  //your code …
}

enquire.register("screen and (min-width: 568px)", {
   match : init,  //always executing when media query is matched OR:
   setup : init,  //only triggered the first time the media query is matched, in combination with:
   deferSetup : true
});

答案 1 :(得分:0)

如果我说得对,那么添加

就足够了
if (window.innerWidth <= 568) return;

init函数或事件处理程序的开头。

答案 2 :(得分:0)

您是否尝试过使用媒体查询? 这里有几个链接:

Conditionally load JavaScript based on media query

Conditional loading of resources with mediaqueries

希望这有助于您找到解决方案。

相关问题