调整脚本大小附加对象,一遍又一遍地执行 [英] Resize script appends object, does it over and over again
问题描述
我在JavaScript文件中包含以下代码:
I have the following code in a JavaScript file:
$(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>');
}}
基本上,它的作用是在宽度小于1280像素时将对象附加到文档的末尾,但是此操作是在每次调整页面大小时将其附加到文档的末尾.
Basically, what it does is append an object to the end of the document if the width is less than 1280 pixels, however what this does is append it every single time the page is resized.
我认为我不能使用once
函数,因为它只会运行一次,然后在下次调整大小时运行,它已经死了.我能做什么?
I don't think I can use the once
function because it would only run it once and then the next time it is resized, it's dead. Anything I can do?
注意:实际上,我确实希望在调整页面大小时对其进行检查,但是这样做的结果是一遍又一遍.
NOTE: I, in fact, DO want it to be checked on the resize of the page, but the effect is that it happens over and over again.
if (windowWidth()>1280 && !$('gearsfloat')) {
$('body').append('<div id="gearsfloat"></div>');
}
以上(由Jason所著)有效不能工作 ,但是当它小于1280时它不会将其删除.我能做些什么吗?
The above (by Jason) works does not work but then it won't delete it when it gets less than 1280. Is there anything I can do?
推荐答案
跟踪该元素是否存在,并在条件发生变化时添加/删除该元素.这样,您只需添加一次,当它不应该存在时将被删除,并且您无需进行任何不必要的添加或删除操作:
Keep track of whether the element exists or not, and add/remove it when the condition changes. That way you will only add it once, it will be removed when it shouldn't be there, and you don't do any unneccesary adding or removing:
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;
}
}
这篇关于调整脚本大小附加对象,一遍又一遍地执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!