2016-10-03 9 views
4

ユーザーが要素を表示または表示するのを待つ方法を教えてください。私は次のような機能を持っていますが、要素が存在するかどうかを確認し、ユーザーに表示されているかどうかを確認するだけではありません。要素がユーザーに表示されるのを待ちます

function waitForElementDisplay (selector, time) { 
    if (document.querySelector(selector) != null) { 
     return true; 
    } else if (timeLimit < timeSince) { 
     return false; 
    } else { 
     timeSince += time; 
     setTimeout(function() { 
      waitForElementDisplay(selector, time, timeLimit, timeSince); 
     }, time); 
    } 
} 
+0

可能性のある重複した[検出の要素が表示されている場合](http://stackoverflow.com/questions/8774089/detect-if-an-element-is-visible) – vlaz

+0

もう一つのことが[ここ](http:// stackov erflow.com/questions/16255423/finding-if-element-is-visible-javascript)と[ここ](http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom) ) – vlaz

+3

* "visible to user" * ..はいくつかの方法で解釈することができます – charlietfl

答えて

1

シンプルな「スリープ」を試していますか?

あなたが使用して要素の負荷を待つことができます。

document.querySelector(selector).onload = function() { 
    // Your code ... 
} 

いくつかの作業スニペットを、それを実行します。

// Triggering load of some element 
 
document.querySelector("body").onload = function() { 
 
    // Setting the timeout and visible to another element 
 
    setTimeout(function() { 
 
     document.querySelector("#my_element").style.display = "block" /* VISIBLE */ 
 
    }, 1000); 
 
}
#my_element{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    display: none; /* INVISIBLE */ 
 
}
<div id="my_element"></div>

をあなたがに設定されているようtimeを待ちたい場合このtimeの後に表示されるselector ..あなたはab単純なsetTimeout()とCSSを出してください。

以下の例を実行するには、それが役に立てば幸い:

// Triggering, in my exemple i've used: WINDOW ONLOAD 
 
window.onload = function() { 
 
    waitForElementDisplay("#my_element", 1000); 
 
} 
 

 
function waitForElementDisplay (selector, time) { 
 
    // Check the DOM Node in console 
 
    console.log(document.querySelector(selector)); 
 
    
 
    // If it's a valid object 
 
    if (typeof document.querySelector(selector) !== "undifined") { 
 
    
 
    // Setting the timeout 
 
    setTimeout(function() { 
 
     document.querySelector(selector).style.display = "block" /* VISIBLE */ 
 
    }, time); 
 
    } 
 
}
#my_element{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    display: none; /* INVISIBLE */ 
 
}
<div id="my_element"></div>

0

あなたが使用できるjQueryの.ready()の

selector.ready(function(){ 
    // do stuff 
}) 
関連する問題