Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 调整脚本大小附加对象,并反复执行_Javascript_Jquery - Fatal编程技术网

Javascript 调整脚本大小附加对象,并反复执行

Javascript 调整脚本大小附加对象,并反复执行,javascript,jquery,Javascript,Jquery,我在JavaScript文件中有以下代码: $(document).ready(function() { detectscreen(); }); $(window).resize(function(){ detectscreen(); }); function windowWidth() { if(!window.innerWidth) { // user is being a git, using ie

我在JavaScript文件中有以下代码:

$(document).ready(function() {
    detectscreen();
});

$(window).resize(function(){
        detectscreen();
    });

    function windowWidth() {
        if(!window.innerWidth) {
            // user is being a git, using ie
            return document.documentElement.clientWidth;
        } else {
            return window.innerWidth;
    }}

    function detectscreen() {
        if (windowWidth()>1280) {
            $('body').append('<div id="gearsfloat"></div>');
    }}
上面的(由Jason编写)不起作用,但是当它小于1280时,它不会删除它。我能做些什么吗?

if(windowWidth()>1280&&!$('gearsfloat')){
if (windowWidth()>1280 && !$('gearsfloat')) {
  $('body').append('<div id="gearsfloat"></div>');
}
$('body')。追加(''); }

首先检查元素是否已存在?

如果不希望在调整窗口大小时调用函数,那么为什么要绑定调整大小函数


文档就绪函数是否总是在调整大小函数之前被调用,因此您可以保证添加元素?

跟踪元素是否存在,并在条件更改时添加/删除它。这样,您只需添加一次,它将在不应该存在时被删除,并且您不会执行任何不必要的添加或删除操作:

var gearsExists = false;

function detectscreen() {
   var shouldExist = windowWidth() > 1280;
   if (shouldExist != gearsExists) {
      if (shouldExist) {
         $('body').append('<div id="gearsfloat"></div>');
      } else {
         $('#gearsfloat').remove();
      }
      gearsExists = shouldExist;
   }
}
var gearsExists=false;
函数detectscreen(){
var shouldExist=windowWidth()>1280;
如果(应该存在!=性别歧视者){
如果(应该存在){
$('body')。追加('');
}否则{
$('#gearsfloat')。删除();
}
性别歧视者=应该存在;
}
}

样式提示-您可以执行以下操作:返回window.innerWidth | | document.documentElement.clientWidth;在您的函数中,以返回设置的值为准,由于某种原因,此操作不起作用,如果屏幕再次调整为小于1280,则需要删除元素。您可以轻松地重写此操作以除去全局变量,或者使用闭包:function detectscreen(){var shouldExist=windowWidth()>1280,gears=$(“#gearsFloat”);if(shouldExist){if(!gears){$('body').append('');}}else{if(gears){gears.remove();}}}gearsExists=shouldExist;}
var gearsExists = false;

function detectscreen() {
   var shouldExist = windowWidth() > 1280;
   if (shouldExist != gearsExists) {
      if (shouldExist) {
         $('body').append('<div id="gearsfloat"></div>');
      } else {
         $('#gearsfloat').remove();
      }
      gearsExists = shouldExist;
   }
}